1

I have created an input that can receive a file. Once the submit button is clicked, I set up a form Data, try to append the file to it, and then launch an axios post request to a server.

Sadly, I don't know how to pass the file to formData:

button.onclick = function(){ let formData = new FormData(); formData.append('myFile', e.dataTransfer.getData("files")); axios.post("/api/upload", formData) .then(response =>{ console.log(response.data)}) .catch(err=> { console.log("error") }) } 

What is the correction to add to e.dataTransfer.getData("files")? The input file can be an image, a pdf, etc. The input looks like that:

<input type="file" multiple/> 

Thanks.

5
  • Your function contains no e, which should be obvious from the error message you get. And missing ) before .catch, plus all kinds of open braces. Commented Jan 14, 2019 at 11:20
  • first of all, try adding "e" as a parameter to the onclick function, so you may access it at the append function on line 3. Commented Jan 14, 2019 at 11:20
  • Also, e.dataTransfer seems to only exist for DragEvents, not ClickEvents. You need to grab the selected file from the input: document.querySelector('input').files[0] (assuming it's the only <input> on the page) Commented Jan 14, 2019 at 11:26
  • @ChrisG It's corrected. I copied the code quickly and poorly on SO, all my apologies. Your selector works. Thank you so much! Commented Jan 14, 2019 at 11:33
  • @ArelSapir Well spotted ;)! Commented Jan 14, 2019 at 11:33

1 Answer 1

1

try to append the formData this way:

form.append('fieldName', 'fileBufferData', 'fileName'); 

Field name will be the name the server look up in the form. The buffer is the data/content of the file. And file name.. well.. it's the file name.

Or it could be because you didn't set the header:

 let form = new FormData(); form.append('field', 'buffer', 'fileName'); axios.post('/api/upload', form, { headers: { 'Content-Type': `multipart/form-data; boundary=${form._boundary}` } }).then((res) => { console.log(res.data); }).catch((err) => { console.log(err); }); 

If this doesn't help it might be a problem on the server side.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.