Skip to content

Instantly share code, notes, and snippets.

Created April 18, 2012 03:23
Show Gist options
  • Save ebidel/2410898 to your computer and use it in GitHub Desktop.
Save ebidel/2410898 to your computer and use it in GitHub Desktop.
Uploading files using xhr.send(FormData) to PHP server
$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
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
See the License for the specific language governing permissions and
limitations under the License.
Author: Eric Bidelman (
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
<title>xhr.send(FormData) Example</title>
<input type="file" name="afile" id="afile" accept="image/*"/>
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();'POST', 'handle_file_upload.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / * 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;
}, false);
<!--[if IE]>
<script src=""></script>
<script>CFInstall.check({mode: 'overlay'});</script>
Copy link

AngeloAlamia commented Mar 12, 2018

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

Copy link

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: ), create a JSON object:

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

add in this after the

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

On the MVC side, you need:

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;

Copy link

Hey! you are great!! thnks !!!

Copy link

Note to anyone finding this via Google Search about Cordova File Upload:
You can use this code on input:file with position:absolute; opacity:0; trick too. Works like a charm.

Copy link

can send(fd) plus other such as image size?

Copy link

Yes. You can still populate the data: {} property as you wish.
What I said just triggers the usual use case for the plugin.

And it still works to this day!

Copy link

PaYo90 commented Jul 16, 2020

I can access rsp.dataUrl my object all the time refuses to read into it, i have it undefined, pls help.

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