Airman Airman - 7 months ago 54
Javascript Question

Can not upload file to perl script using ajax/javascript

I have a form that takes a sinlge file image for upload to a perl script which uses binmode to read and save. The perl script does not seem to be getting the file stream (filesize ends up 0 bytes in size). I'm not sure if I'm passing/using the right name/ref from the html input into the javascript formdata.append. I'm avoiding jquery and xhr version 2 solutions for the time being. I'm determined to make this work if possible.

html input

<input id="newimg" type="file" onchange="changeimg(this.value,dbtable,dbid);">


javascript

function changeimg(filename,dbtable,dbid) {

// ignor "c:\fakepath\" in filename
var filename = document.getElementById('newimg').files[0].name;

var formdata = new FormData();
formdata.append("Content-Type", "multipart/form-data");
formdata.append("dbtable",dbtable);
formdata.append("dbid",dbid);
formdata.append("filename",filename);

if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
var xhr = new XMLHttpRequest();
} else {
// code for IE6, IE5
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("POST","/uploader.pl",true);
xhr.send(formdata);

}


perl snippet which I'm currently using. This same code has been working well for me under "non javascript" page form submits.

#
my $upload_filehandle = $cgi->upload("filename");
#
open (UPLOADFILE, ">$newfile");
binmode UPLOADFILE;
while ( <$upload_filehandle> ) {
print UPLOADFILE;
}
close UPLOADFILE;
#

Answer

None of the variables you are using refer to the file at all. That is why it isn't being included.

Instead of trying to send the filename, send the input.

Replace:

formdata.append("filename",filename);

with:

var file = document.getElementById("newimg").files[0];
formdata.append("newimg", file);

Better yet, stop getting data manually and just send the whole form in one go:

<input id="newimg" name="newimg" type="file" onchange="changeimg(this.form)">

and

function changeimg(form) {
  var formdata = new FormData(form);
  var xhr = new XMLHttpRequest();
  xhr.open("POST","/uploader.pl",true);
  xhr.addEventListener("load", function () { alert("Loaded"); });
  xhr.send(formdata);
}