Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Uploading files using xhr.send(FormData) to PHP server
<?php
$fileName = $_FILES['afile']['name'];
$fileType = $_FILES['afile']['type'];
$fileContent = file_get_contents($_FILES['afile']['tmp_name']);
$dataUrl = 'data:' . $fileType . ';base64,' . base64_encode($fileContent);
$json = json_encode(array(
'name' => $fileName,
'type' => $fileType,
'dataUrl' => $dataUrl,
'username' => $_REQUEST['username'],
'accountnum' => $_REQUEST['accountnum']
));
echo $json;
?>
<!DOCTYPE html>
<!--
Copyright 2012 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Author: Eric Bidelman (ericbidelman@chromium.org)
-->
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
<title>xhr.send(FormData) Example</title>
</head>
<body>
<input type="file" name="afile" id="afile" accept="image/*"/>
<script>
document.querySelector('#afile').addEventListener('change', function(e) {
var file = this.files[0];
var fd = new FormData();
fd.append("afile", file);
// These extra params aren't necessary but show that you can include other data.
fd.append("username", "Groucho");
fd.append("accountnum", 123456);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'handle_file_upload.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete + '% uploaded');
}
};
xhr.onload = function() {
if (this.status == 200) {
var resp = JSON.parse(this.response);
console.log('Server got:', resp);
var image = document.createElement('img');
image.src = resp.dataUrl;
document.body.appendChild(image);
};
};
xhr.send(fd);
}, false);
</script>
<!--[if IE]>
<script src="http://ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js"></script>
<script>CFInstall.check({mode: 'overlay'});</script>
<![endif]-->
</body>
</html>
@markd-up

This comment has been minimized.

Show comment
Hide comment
@markd-up

markd-up Mar 13, 2013

Thanks so much :)
I was looking for how to use $_FILES with an AJAX post and everywhere they only showed the JavaScript but not how to handle the data in PHP.

Thanks so much :)
I was looking for how to use $_FILES with an AJAX post and everywhere they only showed the JavaScript but not how to handle the data in PHP.

@cmosguy

This comment has been minimized.

Show comment
Hide comment
@cmosguy

cmosguy Jul 4, 2013

Does this work in IE? I havin gissues in IE getting things to work properly with the fd FormData.

cmosguy commented Jul 4, 2013

Does this work in IE? I havin gissues in IE getting things to work properly with the fd FormData.

@007ketul

This comment has been minimized.

Show comment
Hide comment
@007ketul

007ketul Nov 26, 2013

hy
"var resp = JSON.parse(this.response);"
whats wrong with this above line in IE ?

hy
"var resp = JSON.parse(this.response);"
whats wrong with this above line in IE ?

@apfelbox

This comment has been minimized.

Show comment
Hide comment
@MrOnyancha

This comment has been minimized.

Show comment
Hide comment
@MrOnyancha

MrOnyancha Feb 12, 2015

below is my code but when i post it to the java server i get nulls on parameters can some one help.

<script> Polymer('my-element', { setFiles: function(e, detail, sender) { formData = new FormData(); ``` for (var i = 0, f; f = sender.files[i]; ++i) { formData.append(sender.name, f, f.name); // alert(sender.name); formData.append("name",this.$.name.value ); // alert( f.description); formData.append("descritpion",this.$.description.value ); //alert(this.$.description.value || f.description); formData.append("title",this.$.title.value); // alert(this.$.title.value || f.title); } this.$.ajax.body = formData; // Override default type set by core-ajax. // Allow browser to set the mime multipart content type itself. this.$.ajax.contentType = null; }, upload: function(e, detail, sender) { // alert(this.$.title.value || f.title); if (!this.$.file.files.length) { alert('Please include a file'); return; } this.$.ajax.go(); }, responseChanged: function() { console.log('Response from server', this.response); }, }); ``` </script>

below is my code but when i post it to the java server i get nulls on parameters can some one help.

<script> Polymer('my-element', { setFiles: function(e, detail, sender) { formData = new FormData(); ``` for (var i = 0, f; f = sender.files[i]; ++i) { formData.append(sender.name, f, f.name); // alert(sender.name); formData.append("name",this.$.name.value ); // alert( f.description); formData.append("descritpion",this.$.description.value ); //alert(this.$.description.value || f.description); formData.append("title",this.$.title.value); // alert(this.$.title.value || f.title); } this.$.ajax.body = formData; // Override default type set by core-ajax. // Allow browser to set the mime multipart content type itself. this.$.ajax.contentType = null; }, upload: function(e, detail, sender) { // alert(this.$.title.value || f.title); if (!this.$.file.files.length) { alert('Please include a file'); return; } this.$.ajax.go(); }, responseChanged: function() { console.log('Response from server', this.response); }, }); ``` </script>
@johnidevo

This comment has been minimized.

Show comment
Hide comment
@johnidevo

johnidevo Feb 13, 2015

Nicee job using FormData in JavaScript to populate $_FILES variable in php, i was wandering some days ago, why not try to populate $_FILES variable, you did it anyway !

Nicee job using FormData in JavaScript to populate $_FILES variable in php, i was wandering some days ago, why not try to populate $_FILES variable, you did it anyway !

@yonaxTics

This comment has been minimized.

Show comment
Hide comment
@yonaxTics

yonaxTics Feb 24, 2015

Nice job, thank you very much (y)

Nice job, thank you very much (y)

@kressly

This comment has been minimized.

Show comment
Hide comment
@kressly

kressly Mar 6, 2015

Please for days now i have been looking for how to modifiy that code and get it to do a multiple upload. Please can you show how to do a multiple upload with this ?

kressly commented Mar 6, 2015

Please for days now i have been looking for how to modifiy that code and get it to do a multiple upload. Please can you show how to do a multiple upload with this ?

@Daniel15

This comment has been minimized.

Show comment
Hide comment
@Daniel15

Daniel15 Jun 5, 2015

@kressly Just include multiple files in the FormData.

Daniel15 commented Jun 5, 2015

@kressly Just include multiple files in the FormData.

@galicialuis

This comment has been minimized.

Show comment
Hide comment
@galicialuis

galicialuis Oct 21, 2015

and if i want to save the image in a carpet or path

and if i want to save the image in a carpet or path

@ahxxan

This comment has been minimized.

Show comment
Hide comment
@ahxxan

ahxxan Mar 17, 2016

{"name":null,"type":null,"dataUrl":"data:;base64,","username":null,"accountnum":null} as output
i am receiving this . can some one help to resolve my issue @chrisp22 could you find solution

ahxxan commented Mar 17, 2016

{"name":null,"type":null,"dataUrl":"data:;base64,","username":null,"accountnum":null} as output
i am receiving this . can some one help to resolve my issue @chrisp22 could you find solution

@ankurgupta1401

This comment has been minimized.

Show comment
Hide comment
@ankurgupta1401

ankurgupta1401 May 22, 2016

You can find a working implementation of uploading file using XMLHttpRequest here.

You can find a working implementation of uploading file using XMLHttpRequest here.

@rod101

This comment has been minimized.

Show comment
Hide comment
@rod101

rod101 Nov 16, 2016

Hi All,
Is there a way I can append the image path without using the file input
I have tried formData.append('avatar', avatar.files[0], 'cc.jpg'); any help please

rod101 commented Nov 16, 2016

Hi All,
Is there a way I can append the image path without using the file input
I have tried formData.append('avatar', avatar.files[0], 'cc.jpg'); any help please

@JuJussel

This comment has been minimized.

Show comment
Hide comment
@JuJussel

JuJussel Aug 28, 2017

Awesome, have been looking for this all day!
Thanks!

Awesome, have been looking for this all day!
Thanks!

@cyber-x-company

This comment has been minimized.

Show comment
Hide comment
@cyber-x-company

cyber-x-company Oct 10, 2017

Thank you very much. Your example help me so much. I looking long time how to upload files to server via xhr. And again, thank you so much.

Thank you very much. Your example help me so much. I looking long time how to upload files to server via xhr. And again, thank you so much.

@AngeloAlamia

This comment has been minimized.

Show comment
Hide comment
@AngeloAlamia

AngeloAlamia Mar 12, 2018

Thanks a lot, after looking all day long I finally found the right script!!!

AngeloAlamia commented Mar 12, 2018

Thanks a lot, after looking all day long I finally found the right script!!!

@navyjax2

This comment has been minimized.

Show comment
Hide comment
@navyjax2

navyjax2 Apr 6, 2018

Note to anyone finding this via Google and working with MVC: To use FormData, you'd have to post using xhr.setRequestHeader("Content-Type","multipart/form-data"); - not included above - but then your server-side will throw an exception if you use

if (!Request.Content.IsMimeMultipartContent() { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); }

which is something it should never do, so I'm convinced FormData can only be used with PHP. Better to get the file into a base64 string (I have an example here: https://stackoverflow.com/questions/37134433/convert-input-file-to-byte-array/49676679#49676679 ), create a JSON object:

var dataObj = { afile: myBase64file, username: "Groucho", accountnum: 123456, };,

add in this after the xhr.open():
xhr.setRequestHeader("Content-Type","application/json;charset=UTF-8");

then do xhr.send(JSON.stringify(dataObj)); at the end.

On the MVC side, you need:

[System.Web.Http.HttpPost]
public virtual ActionResult Post([FromBody]MyModel myModelObject) { ... }

You'll need to have a model:
public class MyModel {
public string afile { get; set; }
public string username { get; set; }
public int accountnum { get; set; }
}

Inside the Post, the parameters should be accessible: string file = myModelObject.afile;

navyjax2 commented Apr 6, 2018

Note to anyone finding this via Google and working with MVC: To use FormData, you'd have to post using xhr.setRequestHeader("Content-Type","multipart/form-data"); - not included above - but then your server-side will throw an exception if you use

if (!Request.Content.IsMimeMultipartContent() { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); }

which is something it should never do, so I'm convinced FormData can only be used with PHP. Better to get the file into a base64 string (I have an example here: https://stackoverflow.com/questions/37134433/convert-input-file-to-byte-array/49676679#49676679 ), create a JSON object:

var dataObj = { afile: myBase64file, username: "Groucho", accountnum: 123456, };,

add in this after the xhr.open():
xhr.setRequestHeader("Content-Type","application/json;charset=UTF-8");

then do xhr.send(JSON.stringify(dataObj)); at the end.

On the MVC side, you need:

[System.Web.Http.HttpPost]
public virtual ActionResult Post([FromBody]MyModel myModelObject) { ... }

You'll need to have a model:
public class MyModel {
public string afile { get; set; }
public string username { get; set; }
public int accountnum { get; set; }
}

Inside the Post, the parameters should be accessible: string file = myModelObject.afile;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment