Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give a Blob uploaded as FormData a file name?

I am currently uploading images pasted from the clipboard with the following code:

// Turns out getAsFile will return a blob, not a file var blob = event.clipboardData.items[0].getAsFile(),      form = new FormData(),     request = new XMLHttpRequest(); form.append("blob",blob); request.open(             "POST",             "/upload",             true         ); request.send(form); 

Turns out the uploaded form field with receive a name similar to this: Blob157fce71535b4f93ba92ac6053d81e3a

Is there any way to set this or receive this file name client side, without doing any server side communication?

like image 585
jontro Avatar asked Jul 12 '11 13:07

jontro


People also ask

How do you add a name to a blob file?

Go to the table which contains the blob file. Add a new column in the table. For example, name the new column as filename with a string data type. This field stores the uploaded blob's filename.

How do you send a file using multipart form data?

Follow this rules when creating a multipart form: Specify enctype="multipart/form-data" attribute on a form tag. Add a name attribute to a single input type="file" tag. DO NOT add a name attribute to any other input, select or textarea tags.


2 Answers

For Chrome, Safari and Firefox, just use this:

form.append("blob", blob, filename); 

(see MDN documentation)

like image 59
Chiguireitor Avatar answered Oct 04 '22 05:10

Chiguireitor


Adding this here as it doesn't seem to be here.

Aside from the excellent solution of form.append("blob",blob, filename); you can also turn the blob into a File instance:

var blob = new Blob([JSON.stringify([0,1,2])], {type : 'application/json'}); var fileOfBlob = new File([blob], 'aFileName.json'); form.append("upload", fileOfBlob); 
like image 32
Noitidart Avatar answered Oct 04 '22 05:10

Noitidart