Resume HTTP Post/upload with Indy

拜拜、爱过 提交于 2019-12-03 17:11:08
Remy Lebeau

As I told you in your earlier question, you have to post a TStream containing the remaining file data to upload. Don't use TIdMultipartFormDataStream.AddFile(), as that will send the entire file. Use the TStream overloaded version of TIdMultipartFormDataStream.AddFormField() instead.

And TIdHTTP is not designed to respect the ContentRange... properties. Most of the Request properties merely set the corresponding HTTP headers only, they do not influence the data. That is why your edits broke it.

Try this:

IdHttp.Head('http://localhost/_tests/resume/large-file.bin');
FileSize := IdHttp.Response.ContentLength;

FileStrm := TFileStream.Create('D:\large-file.bin', fmOpenRead or fmShareDenyWrite);
try
  if FileSize < FileStrm.Size then
  begin
    FileStrm.Position := FileSize;

    Stream := TIdMultipartFormDataStream.Create;
    try
      with Stream.AddFormField('upload_file', 'application/octet-stream', '', FileStrm, 'large-file.bin') do
      begin
        HeaderCharset  := 'utf-8';
        HeaderEncoding := '8';
      end;

      with IdHTTP do
      begin
        with Request do
        begin
          ContentRangeStart := FileSize + 1;
          ContentRangeEnd   := FileStrm.Size;
        end;

        Post('http://localhost/_tests/resume/t1.php', Stream);
      end;
    finally
      Stream.Free;
    end;
  end;
finally
  FileStrm.Free;
end;

With that said, this is a GROSS MISUSE of HTTP and multipart/form-data. For starters, the ContentRange values are in the wrong place. You are applying them to the entire Request as a whole, which is wrong. They would need to be applied at the FormField instead, but TIdMultipartFormDataStream does not currently support that. Second, multipart/form-data was not designed to be used like this anyway. It is fine for uploading a file from the beginning, but not for resuming a broken upload. You really should stop using TIdMultipartFormDataStream and just pass the file data directly to TIdHTTP.Post() like I suggested earlier, eg:

FileStrm := TFileStream.Create('D:\large-file.bin', fmOpenRead or fmShareDenyWrite);
try
  IdHTTP.Post('http://localhost/_tests/upload.php?name=large-file.bin', FileStrm);
finally
  FileStrm.Free;
end;

.

IdHTTP.Head('http://localhost/_tests/files/large-file.bin');
FileSize := IdHTTP.Response.ContentLength;

FileStrm := TFileStream.Create('D:\large-file.bin', fmOpenRead or fmShareDenyWrite);
try
  if FileSize < FileStrm.Size then
  begin
    FileStrm.Position := FileSize;
    IdHTTP.Post('http://localhost/_tests/resume.php?name=large-file.bin', FileStrm);
  end;
finally
  FileStrm.Free;
end;

I already explained earlier how to access the raw POST data in PHP.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!