Home  >  Article  >  Web Front-end  >  How to Resolve \"Request Rejected: No Multipart Boundary\" Error in XMLHttpRequest File Upload?

How to Resolve \"Request Rejected: No Multipart Boundary\" Error in XMLHttpRequest File Upload?

Barbara Streisand
Barbara StreisandOriginal
2024-10-18 16:42:30788browse

How to Resolve

XMLHttpRequest File Upload with MultipartFormData

When attempting to upload a file using XMLHttpRequest, you may encounter the following error: "The request was rejected because no multipart boundary was found." To resolve this issue, follow these steps:

1. Remove the Custom xhr.file Property

Remove the line xhr.file = file; as it is not used for multipart file uploads.

2. Use the FormData Object

Instead of xhr.send(file);, use FormData to wrap the file into a multipart/form-data post data object:

<code class="javascript">var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);</code>

3. Access the File on the Server

After sending the FormData, you can access the file in $_FILES['thefile'] (assuming PHP is used on the server).

Additional Notes:

  • Use MDC and Mozilla Hack demos as resources for file uploads.
  • The original code attempt sent the file as raw post data, which requires manual parsing on the server (not always feasible).

By following these steps, you should be able to successfully upload files using Ajax XMLHttpRequest with the correct multipart/form-data boundary.

The above is the detailed content of How to Resolve \"Request Rejected: No Multipart Boundary\" Error in XMLHttpRequest File Upload?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn