I am trying to figure out how to send a file and paramaters within the same XMLHttpRequest. Is this possible?
Obviously I can do xhr.send(file+params) or xhr.(file,params). And I don't think I can set two different request headers to do this...
xhr.setRequestHead('X_FILENAME', file.name)
xhr.send(file);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(params);
Is there some way to send the params without having to use GET, or a secondary xhr request?
The XMLHttpRequest method send() sends the request to the server. If the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events. If the request is synchronous, this method doesn't return until the response has arrived.
XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.
The XHR specification says that GET is used without sending data to the server by the send method, and that you use POST in the other case: If stored method is GET act as if the data argument is null. So practically we use GET to load a document or run a script, and POST to pass parameters to a script on the server.
The XMLHttpRequest response property returns the response's body content as an ArrayBuffer , a Blob , a Document , a JavaScript Object , or a string, depending on the value of the request's responseType property.
If you rely on browser which supports FormData
, you can use the code below (JavaScript):
var formData = new FormData();
formData.append('param1', 'myParam');
formData.append('param2', 12345);
formData.append('uploadDir', 'public-data');
formData.append('myfile', file);
xhr.send(formData);
Then, on your server side you can have access to your variables by using this code (PHP):
<?
$param1 = $_POST['param1']; //myParam
$param2 = $_POST['param2']; //12345
$uploaddir = $_POST['uploadDir']; //public-data
$fileName = $_FILES['myfile']['name'];
$fileZise = $_FILES['myfile']['size'];
$uploaddir = getcwd().DIRECTORY_SEPARATOR.$uploaddir.DIRECTORY_SEPARATOR;
$uploadfile = $uploaddir.basename($fileName);
move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile);
echo $fileName.' ['.$fileZise.'] was uploaded successfully!';
?>
To get all parameters of $_FILES['myfile']
, use var_dump($_FILES["myfile"])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With