Post form fields + file using xhr, and reconstruct server side
I'm trying to submit an HTML form's data to a php script via an XHR request.
I've hit a problem with the code however which I suspect has something to do with the back-end side of things, however might be doing something incorrect in javascript which is as follows:
var fd = new FormData();
fd.append("title", $('#uploadVidTitle').val());
fd.append("proj", $('#uploadVidProject').val());
fd.append("desc", $('#uploadVidDesc').val());
fd.append("action", $('#uploadAction').val());
console.log(fd);
fd.append("uploadFile", document.getElementById('videoUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress"开发者_运维技巧, uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "actions.php", false);
xhr.send(fd);
Currently in the php code I'm getting the forms contents via the $_POST["name"]
method, however cannot retrieve the files contents using $_FILES["name"]
. Any pointers would be greatly appreciated.
I think problem at server side. Ty this
foreach ($_FILES as $id => $val)
if (isset($_FILES[$id]['name']) && $_FILES[$id]['name'] != '')
{
//process files
Retrieving file names by using $_FILES[$id]['name'] worked for me.
You might want to try setting some request headers before sending the request:
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
or
xhr.setRequestHeader("Content-type", "multipart/form-data");
Also inspect the $_FILES superglobal after POST request is sent to see if any files can be accessed from it.
精彩评论