如何用Delphi(Rio)的TRestClient库向WordPress上传媒体文件
Fixing WordPress REST API Media Upload Error in Delphi
First, let's break down the error you're seeing: rest_upload_no_content_disposition means WordPress isn't receiving the file with the required Content-Disposition header. This header tells the API the filename and field name for the uploaded file, and your current code sends raw image data instead of wrapping it in the multipart form request that WordPress expects for media uploads.
Here's the corrected Delphi code to properly upload images to the WordPress REST API:
procedure Tfrm_Main.btn_MediaClick(Sender: TObject); var jpgFoto: TMemoryStream; FileName: string; begin ResetRESTComponentsToDefaults; RESTClient.BaseURL := lbledt_BaseWProp.Text; RESTClient.Authenticator := HTTPBasic_DelphiPRAXiS; RESTRequest.Resource := 'media'; HTTPBasic_DelphiPRAXiS.Username := lbledt_Usuario.Text; HTTPBasic_DelphiPRAXiS.Password := lbledt_Clave.Text; FileName := 'beautiful-blowball-dandelion-vector-background.jpg'; jpgFoto := TMemoryStream.Create; try jpgFoto.LoadFromFile('t:\' + FileName); jpgFoto.Position := 0; // Set request to use multipart form data (required for file uploads) RESTRequest.ContentType := TRESTContentType.ctMULTIPART_FORM_DATA; // Add the file as a form field with correct disposition headers RESTRequest.AddFormField('file', jpgFoto, TRESTContentType.ctIMAGE_JPEG, FileName); RESTRequest.Method := TRESTRequestMethod.rmPOST; RESTRequest.Execute; // Optional: Parse the response to get media ID/URL for later use if Assigned(RESTResponse.JSONValue) then ShowMessage('Upload successful! Media ID: ' + RESTResponse.JSONValue.GetValue<Integer>('id').ToString); finally jpgFoto.Free; end; end;
Key Changes Explained:
- Multipart Form Data: We set
RESTRequest.ContentTypetoctMULTIPART_FORM_DATA—this is the standard format for file uploads to REST APIs, including WordPress. - Form Field Wrapping: Instead of
AddBody, we useAddFormFieldto package the image stream into a field namedfile(the exact field name WordPress expects). This automatically adds the missingContent-Dispositionheader with the filename. - Safe Stream Handling: The
try/finallyblock ensures the memory stream is always freed, even if an error occurs during upload.
After Successful Upload:
The JSON response will include critical metadata like:
id: The unique media ID you can use to link the image to a post (via the post'sfeatured_mediafield)source_url: Direct URL to the uploaded imageguid: The permanent link to the media item
Quick Checks to Avoid Future Issues:
- Ensure your WordPress site's REST API is enabled (default in modern WordPress versions)
- Confirm your user account has the
upload_filescapability (editors/admins have this by default) - Double-check your base URL ends with
/wp-json/wp/v2/(e.g.,https://your-site.com/wp-json/wp/v2/) to target the correct API endpoint
内容的提问来源于stack exchange,提问作者Speaker
相关产品推荐
相关产品推荐

