Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Uploading a file... without a file

I am trying to fake a file upload without actually using a file input from the user. The file's content will be dynamically generated from a string.

Is this possible? Have anyone ever done this before? Are there examples/theory available?

To clarify, I know how to upload a file using AJAX techniques using a hidden iframe and friends - the problem is uploading a file that is not in the form.

I am using ExtJS, but jQuery is feasible as well since ExtJS can plug into it (ext-jquery-base).

like image 962
LiraNuna Avatar asked Feb 04 '10 09:02

LiraNuna


People also ask

How can I upload a file without form?

It is like a "multipart/form-data" upload without a form. You can also upload the file directly as content inside the body of the POST request using xmlHttpRequest like this: var xmlHttpRequest = new XMLHttpRequest(); var file = ...file handle... var fileName = ...file name...

How do you append files in input type file multiple before uploading?

You could add a new <input type="file"> whenever you finished uploading the previous files and hide the previous input. This way you keep adding a new input every time you want to add more files and prevent the previous input from being overwritten.


1 Answers

If you don't need support for older browsers you can use the FormData Object, which is part of the File API:

var formData = new FormData(); var blob = new Blob(['Lorem ipsum'], { type: 'plain/text' }); formData.append('file', blob,'readme.txt');  var request = new XMLHttpRequest(); request.open('POST', 'http://example.org/upload'); request.send(formData); 

File Api is supported by all current browsers (IE10+)

  • https://developer.mozilla.org/en-US/docs/Web/API/FormData
  • http://caniuse.com/#feat=fileapi
like image 178
Josa Avatar answered Oct 11 '22 11:10

Josa