It looks like the issue might be related to how the FormData is being constructed and sent with the XMLHttpRequest. Specifically, the Content-Type header might be incorrectly set or not set at all, which can affect how the server interprets the incoming request.
Here are a few steps to troubleshoot and potentially fix the issue:
-
Ensure the
enctypeis set correctly in the XMLHttpRequest: When sending files with FormData and XMLHttpRequest, you need to ensure that theContent-Typeheader is set tomultipart/form-data. However, when usingFormDatawithXMLHttpRequest, this should be handled automatically, and you should not set theContent-Typeheader manually. This allows the browser to set the boundary in theContent-Typewhich is necessary for parsing the multipart form data on the server.Modify your
uploadFilefunction to remove any manual setting of theContent-Typeheader if present. Here's how you might adjust the function:function uploadFile(file, progressCallback, successCallback) { var key = createStorageKey(file); var formData = createFormData(key, file); var xhr = new XMLHttpRequest(); xhr.open("post", sendRequestUrl, true); // Do not set Content-Type manually // xhr.setRequestHeader('Content-Type', 'multipart/form-data'); xhr.upload.addEventListener("progress", function(event) { var progress = event.loaded / event.total * 100; progressCallback(progress); }); xhr.addEventListener("load", function(event) { if (xhr.status == 204) { var attributes = { url: HOST + key, href: HOST + key + "?content-disposition=attachment" }; successCallback(attributes); } }); xhr.send(formData); } -
Check the server-side configuration: Ensure that your Laravel backend is correctly configured to handle file uploads. Check your
php.inisettings forfile_uploads,upload_max_filesize,post_max_size, andmax_file_uploadsto ensure they are set to reasonable values. -
Debugging the request: Before sending the request, you can log the
FormDatacontents as you've done, but also consider checking the network request in the browser's developer tools to see the actual payload and headers being sent. -
Laravel Controller Adjustment: Make sure that your Laravel route handling the file upload is correctly receiving the file. You can debug by returning the entire request object or specific parts of it to see what data is actually making it to the server.
public function storePostImages(Request $request) { return response()->json(['request' => $request->all()], 200); }
By following these steps, you should be able to diagnose why $request->hasFile('file') is returning false and fix the issue accordingly.