首頁  >  文章  >  web前端  >  如何解決使用Ajax XMLHttpRequest上傳檔案時出現的多部分邊界錯誤?

如何解決使用Ajax XMLHttpRequest上傳檔案時出現的多部分邊界錯誤?

DDD
DDD原創
2024-10-18 16:42:08303瀏覽

How to Resolve the Multipart Boundary Error in File Uploads Using Ajax XMLHttpRequest?

File Upload Utilizing Ajax XMLHttpRequest: Resolving Multipart Boundary Error

In an attempt to transfer a file using XMLHttpRequest, you might encounter the following error:

The request was rejected because no multipart boundary was found.

This error signifies that your code lacks the correct approach to handling multipart form data. To rectify this issue, let's address two key areas:

  1. XHR file property: The line xhr.file = file; is superfluous. The file object should not be assigned in this manner.
  2. File Transmission: Modifying xhr.send(file); won't transfer the file effectively. Instead, use the FormData object to construct the multipart/form-data payload:
var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);

By utilizing FormData, the file becomes accessible through the PHP variable $_FILES['thefile'].

Remember to consult documentation and demos from MDC and Mozilla Hack for further guidance on this topic.

Previous Incorrect Suggestion:

The earlier answer incorrectly stated that xhr.send(file); transmits the raw post data. While it does send the file, it's imperative to employ FormData to ensure proper parsing on the server. Therefore, the above correction is crucial for achieving the desired functionality.

以上是如何解決使用Ajax XMLHttpRequest上傳檔案時出現的多部分邊界錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn