【问题标题】:Delphi upload image HTTP serverDelphi上传图片HTTP服务器
【发布时间】:2014-10-13 20:40:15
【问题描述】:

在我的 VCL 应用程序中,我有一个 http 服务器。我正在尝试从浏览器上传图像。下面是 commandGet 过程的代码:

procedure TForm6.HTTPServerCommandGet(AContext: TIdContext;
  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
  imageStream: TMemoryStream;
begin
  if Pos('command=addImage', ARequestInfo.UnparsedParams) > 0 then
  begin
    AResponseInfo.ContentText := UploadImageForm;
  end
  else if Pos('command=saveImage', ARequestInfo.UnparsedParams) > 0 then
  begin
    imageStream := TMemoryStream.Create;

    try
      ARequestInfo.PostStream.Seek(0, soFromBeginning);
      imageStream.LoadFromStream(ARequestInfo.PostStream);
      imageStream.SaveToFile('picture.jpeg');
    finally
      imageStream.Free;
    end;
  end;
end;

UploadImageForm的代码如下:

 function UploadImageForm: string;
 var
   uploadImageHTMLForm: TStringBuilder;
 begin
   uploadImageHTMLForm := TStringBuilder.Create;

   try
     // by default enctype is application/x-www-form-urlencoded
     // uploadImageHTMLForm.AppendLine('<form action="/?command=saveImage" method="post">');
     // EDIT
     uploadImageHTMLForm.AppendLine('<form action="/?command=saveImage" method="post" enctype="multipart/form-data">');
     uploadImageHTMLForm.AppendLine('<input type="file" name="uploadField">');
     uploadImageHTMLForm.AppendLine('<input type="submit">');
     uploadImageHTMLForm.AppendLine('</form>');
     Result := uploadImageHTMLForm.ToString;
   finally
     uploadImageHTMLForm.Free;
   end;
 end;

问题是,当我选择一个 .jpeg 文件并单击提交时,ARequestInfo.PostStream 为空(我在 CreatePostStream 上创建它)。知道如何解决它。

【问题讨论】:

    标签: delphi file-upload httpserver forms http-post


    【解决方案1】:

    带有type=file 的HTML 表单&lt;input&gt; 元素应使用enctype="multipart/form-data"(参见https://stackoverflow.com/a/2436725/80901)。

    但是,TIdHTTPServer 不支持 multipart/form-data - 请参阅 TIdHTTPServer file upload

    需要额外的代码才能从请求正文中提取文件内容。 (之前在 Embarcadero 和 Indy 论坛上已经发布过这样的例子。)

    【讨论】:

    • 我应该使用 aRequestInfo 的哪个属性(RawHeaders、PostStream 或其他)。你能发个链接吗,因为我还没有找到有用的东西
    • 感谢您提供有用的资源。你又帮我解决了我的问题:)
    猜你喜欢
    • 2014-06-05
    • 2015-10-20
    • 1970-01-01
    • 2011-06-01
    相关资源
    最近更新 更多