4

I have a form builder and I want to add drag and drop file capabilities.

Where I'm stuck is that all the resources I'm coming across upload the image via xhr when dropped. I want the image to persist until the form is submitted.

Ideally the event.dataTransfer.files[0] object would be transferred to the <input type="file" ...value="[dropped-file]"> element.

Currently I'm unable to make this happen. Do they use compatible data types?

3
  • Why is it a problem to use XHR? Simply send the request after the form has been submitted, or submit the entire form w/ the file via ajax. Read up on FormData for more info. Commented Jul 25, 2013 at 18:58
  • My understanding is that FormData doesn't work well with older (8-9) IEs. Am I wrong? Commented Jul 25, 2013 at 19:16
  • That is true (FormData doesn't exist in those browsers), but irrelevant, since you cannot upload files via drag & drop in those browsers anyway. Commented Jul 25, 2013 at 19:21

1 Answer 1

3

You could just create and send a form after your drop event has occurred, and the user clicks a conf button. Heres the gist of it: (not tested).

function uploadFile(file) { var form = new FormData(), xhr = new XMLHttpRequest(); form.append('media', file); xhr.open('POST', '/myurl/'); xhr.onprogress = function(e) { showProgress(); } xhr.onload = function(e) { showSuccessConf(); } xhr.send(form); } uploadFile(event.dataTransfer.files[0]); 
Sign up to request clarification or add additional context in comments.

3 Comments

Was hoping to send it via the normal $_POST but I may have to switch over to an xhr option. Thanks for the reply.
This will sent a POST request. As far as your server is concerned, there is no difference between a form submit and a FormData object sent via POST using XHR.
This doesn't really answer the question. I want to be able to upload the file through the usual file input OR by dragging/dropping to a custom zone. In any case the form has several input fields and the file input is just one of them, so I'd like to submit the whole form at once the traditional way: with a simple form submission.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.