Question

In Delphi XE2, I am trying to upload the lines of a memo to a file on my webspace with IdHTTP.Put:

procedure TForm1.btnUploadClick(Sender: TObject);
var
  StringToUpload: TStringStream;
begin
  StringToUpload := TStringStream.Create('');
  try
    StringToUpload.WriteString(memo.Lines.Text);
    // Error: HTTP/1.1 405 Method Not Allowed.
    IdHTTP1.Put(edtOnlineFile.Text, StringToUpload); 
  finally
    StringToUpload.Free;
  end;
end;

But I always get this error message:

enter image description here

So what must I do to avoid the error and make the upload?

Was it helpful?

Solution

It means the HTTP server does not support the PUT method on that URL (if at all). There is nothing you can do about that. You will likely have to upload your data another way, usually involving POST instead, or a completely different protocol, like FTP.

BTW, when using TStringStream like this, don't forget to reset the Position if you use the WriteString() method:

StringToUpload.WriteString(memo.Lines.Text);
StringToUpload.Position := 0;

Otherwise, use the constructor instead:

StringToUpload := TStringStream.Create(memo.Lines.Text);

OTHER TIPS

Thanks for the above code, here is perhaps a little more information with a little helper function to assist with that Stream constructor which I found works for any string you pass through, even it contains binary stuff.

  //Helper function to make JSON string correct for processing with POST / GET
  function StringToStream(const AString: string): TStream;
  begin
     Result := TStringStream.Create(AString);
  end;

 //somewhere in your code, I am posting to Spring REST, encoding must be utf-8
 IdHTTP1.Request.ContentType := 'application/json'; //very important
 IdHTTP1.Request.ContentEncoding := 'utf-8'; //which encoding?
 response := IdHTTP1.Put(URL, StringToStream(body)); //response,URL,body are declared as String
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top