Upload Files with Ajax XMLHttpRequest: Resolving the "No Multipart Boundary" Error
When attempting to upload files using XMLHttpRequest, you may encounter the "The request was rejected because no multipart boundary was found" error. To address this issue, let's delve into the provided code and identify the potential causes.
The following code snippet is intended to upload a file using XMLHttpRequest:
<code class="javascript">var url = "http://localhost:80/..."; $(document).ready(function(){ document.getElementById('upload').addEventListener('change', function(e) { var file = this.files[0]; var xhr = new XMLHttpRequest(); // xhr.file = file; // not necessary if you create scopes like this xhr.addEventListener('progress', function(e) { var done = e.position || e.loaded, total = e.totalSize || e.total; console.log('xhr progress: ' + (Math.floor(done/total*1000)/10) + '%'); }, false); if ( xhr.upload ) { xhr.upload.onprogress = function(e) { var done = e.position || e.loaded, total = e.totalSize || e.total; console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%'); }; } xhr.onreadystatechange = function(e) { if ( 4 == this.readyState ) { console.log(['xhr upload complete', e]); } }; xhr.open('post', url, true); xhr.setRequestHeader("Content-Type", "multipart/form-data"); xhr.send(file); }, false); });</code>
To resolve the aforementioned error, two key points need to be addressed:
<code class="javascript">... var formData = new FormData(); formData.append("thefile", file); xhr.send(formData); ...</code>
By creating a FormData object and appending the file, you ensure that the data is correctly structured and ready to be processed on the server. The file will now be accessible in $_FILES['thefile'] (if you are using PHP on the server-side), allowing you to handle it appropriately.
Referring to documentation resources such as MDC and Mozilla demos can provide valuable guidance when faced with such issues.
The above is the detailed content of How to Resolve the \'No Multipart Boundary\' Error in Ajax XMLHttpRequest File Upload?. For more information, please follow other related articles on the PHP Chinese website!