1

EDIT - It must run when the user submits, I would prefer to avoid an Ajax call if possible,

I'm having a problem sending a file to the server using the Javascript FormData object. While posting everything here will obfuscate the issue and prompt a lot of 'why didn't you do this?' questions.

As part of my interface, a user drags and drops a file onto a part of the web page. This prompts the following code to run:

var data = new FormData();
if (selectedFile != null) {
    data.append(selectedFile.name, selectedFile);
}
$('#myForm').submit();

The above code works correctly, other than the problem that I am having. While the rest of the form is submitted properly, I am not getting the file I am trying to upload - I know this because I looked at the entirety of the network request, and it simply wasn't there. There's no (obvious, at least) bug here, but there must be something that I am overlooking, forgetting, or simply don't know how to do.

FWIW, this is part of a drag and drop file submittal interface where for one reason or another the ones that I tried were not suitable.

Ev Conrad
  • 323
  • 4
  • 17
  • 1
    `FormData` is used with AJAX. When you use `$('#myForm').submit()`, it just submits the form's fields, not any Javascript variables. – Barmar Dec 08 '14 at 21:23
  • What library are you using for adding the file? (also what is `selectedFile` set to?) – Petah Dec 08 '14 at 21:35
  • @Barmar - Thanks, while it seems obvious to me now, your comment helped me clarify my thinking. I figured I was missing something, but I was thinking/hoping that FormData would 'magically' add this in. I will dump it into a form field before submittal. – Ev Conrad Dec 08 '14 at 21:50
  • @Petah - I'm just using e.dataTransfer.files[0], where e is the event data for a drop event listener on a DIV. I'm positive that this is working properly, and that the FormData object doesn't connect at all to any form variables. – Ev Conrad Dec 08 '14 at 21:55
  • 1
    @EvConrad You could look into reading the file and submitting it as an encoded hidden input using `FileReader`: http://codereview.stackexchange.com/questions/38083/data-uri-encoder MDN docs: https://developer.mozilla.org/en-US/docs/Web/API/FileReader – Petah Dec 08 '14 at 22:28
  • @Petah I ended up doing pretty much this. Thanks! – Ev Conrad Dec 09 '14 at 17:42

0 Answers0