Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XHR.send(file + params)?

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?

like image 704
CJT3 Avatar asked Mar 05 '13 07:03

CJT3


People also ask

What does XHR Send do?

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.

What is an XHR file?

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.

Is XHR a post or get?

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.

What is XHR response?

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.


1 Answers

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"])

like image 97
Nolesh Avatar answered Sep 30 '22 12:09

Nolesh