How can I upload files asynchronously?
up vote
2678
down vote
favorite
I would like to upload a file asynchronously with jQuery. This is my HTML:
<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>
And here my Jquery
code:
$(document).ready(function () {
$("#uploadbutton").click(function () {
var filename = $("#file").val();
$.ajax({
type: "POST",
url: "addFile.do",
enctype: 'multipart/form-data',
data: {
file: filename
},
success: function () {
alert("Data Uploaded: ");
}
});
});
});
Instead of the file being uploaded, I am only getting the filename. What can I do to fix this problem?
Current Solution
I am using the jQuery Form Plugin to upload files.
javascript jquery ajax asynchronous upload
|
show 3 more comments
up vote
2678
down vote
favorite
I would like to upload a file asynchronously with jQuery. This is my HTML:
<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>
And here my Jquery
code:
$(document).ready(function () {
$("#uploadbutton").click(function () {
var filename = $("#file").val();
$.ajax({
type: "POST",
url: "addFile.do",
enctype: 'multipart/form-data',
data: {
file: filename
},
success: function () {
alert("Data Uploaded: ");
}
});
});
});
Instead of the file being uploaded, I am only getting the filename. What can I do to fix this problem?
Current Solution
I am using the jQuery Form Plugin to upload files.
javascript jquery ajax asynchronous upload
70
you are only getting the file name because your var filename is getting the value of $('#file'), not the file that lies in the input
– Jimmy
Nov 3 '09 at 16:01
21
Here's a good one: http://blueimp.github.io/jQuery-File-Upload/ - HTML5 ajax uploading - Graceful fallback to iframes for unsupported browsers - Multi-file async upload We've used it and it works great. (Documentation here)
– Ashish Panery
Apr 12 '13 at 18:35
jQuery Form Plugin seems the most simple-to-use and cross-browser compatible way... am I right ?
– Lyth
Sep 18 '13 at 12:32
3
Check also this: stackoverflow.com/questions/6974684/…, here it explains how to achieve it via jQuery
– Chococroc
Jan 15 '14 at 12:09
2
@Jimmy How would he get the get the file that lies in the input instead?
– alex
Dec 5 '14 at 18:05
|
show 3 more comments
up vote
2678
down vote
favorite
up vote
2678
down vote
favorite
I would like to upload a file asynchronously with jQuery. This is my HTML:
<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>
And here my Jquery
code:
$(document).ready(function () {
$("#uploadbutton").click(function () {
var filename = $("#file").val();
$.ajax({
type: "POST",
url: "addFile.do",
enctype: 'multipart/form-data',
data: {
file: filename
},
success: function () {
alert("Data Uploaded: ");
}
});
});
});
Instead of the file being uploaded, I am only getting the filename. What can I do to fix this problem?
Current Solution
I am using the jQuery Form Plugin to upload files.
javascript jquery ajax asynchronous upload
I would like to upload a file asynchronously with jQuery. This is my HTML:
<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>
And here my Jquery
code:
$(document).ready(function () {
$("#uploadbutton").click(function () {
var filename = $("#file").val();
$.ajax({
type: "POST",
url: "addFile.do",
enctype: 'multipart/form-data',
data: {
file: filename
},
success: function () {
alert("Data Uploaded: ");
}
});
});
});
Instead of the file being uploaded, I am only getting the filename. What can I do to fix this problem?
Current Solution
I am using the jQuery Form Plugin to upload files.
javascript jquery ajax asynchronous upload
javascript jquery ajax asynchronous upload
edited Oct 31 '17 at 16:37
Kevin B
85k11134155
85k11134155
asked Oct 3 '08 at 10:22
Sergio del Amo
30.9k62138173
30.9k62138173
70
you are only getting the file name because your var filename is getting the value of $('#file'), not the file that lies in the input
– Jimmy
Nov 3 '09 at 16:01
21
Here's a good one: http://blueimp.github.io/jQuery-File-Upload/ - HTML5 ajax uploading - Graceful fallback to iframes for unsupported browsers - Multi-file async upload We've used it and it works great. (Documentation here)
– Ashish Panery
Apr 12 '13 at 18:35
jQuery Form Plugin seems the most simple-to-use and cross-browser compatible way... am I right ?
– Lyth
Sep 18 '13 at 12:32
3
Check also this: stackoverflow.com/questions/6974684/…, here it explains how to achieve it via jQuery
– Chococroc
Jan 15 '14 at 12:09
2
@Jimmy How would he get the get the file that lies in the input instead?
– alex
Dec 5 '14 at 18:05
|
show 3 more comments
70
you are only getting the file name because your var filename is getting the value of $('#file'), not the file that lies in the input
– Jimmy
Nov 3 '09 at 16:01
21
Here's a good one: http://blueimp.github.io/jQuery-File-Upload/ - HTML5 ajax uploading - Graceful fallback to iframes for unsupported browsers - Multi-file async upload We've used it and it works great. (Documentation here)
– Ashish Panery
Apr 12 '13 at 18:35
jQuery Form Plugin seems the most simple-to-use and cross-browser compatible way... am I right ?
– Lyth
Sep 18 '13 at 12:32
3
Check also this: stackoverflow.com/questions/6974684/…, here it explains how to achieve it via jQuery
– Chococroc
Jan 15 '14 at 12:09
2
@Jimmy How would he get the get the file that lies in the input instead?
– alex
Dec 5 '14 at 18:05
70
70
you are only getting the file name because your var filename is getting the value of $('#file'), not the file that lies in the input
– Jimmy
Nov 3 '09 at 16:01
you are only getting the file name because your var filename is getting the value of $('#file'), not the file that lies in the input
– Jimmy
Nov 3 '09 at 16:01
21
21
Here's a good one: http://blueimp.github.io/jQuery-File-Upload/ - HTML5 ajax uploading - Graceful fallback to iframes for unsupported browsers - Multi-file async upload We've used it and it works great. (Documentation here)
– Ashish Panery
Apr 12 '13 at 18:35
Here's a good one: http://blueimp.github.io/jQuery-File-Upload/ - HTML5 ajax uploading - Graceful fallback to iframes for unsupported browsers - Multi-file async upload We've used it and it works great. (Documentation here)
– Ashish Panery
Apr 12 '13 at 18:35
jQuery Form Plugin seems the most simple-to-use and cross-browser compatible way... am I right ?
– Lyth
Sep 18 '13 at 12:32
jQuery Form Plugin seems the most simple-to-use and cross-browser compatible way... am I right ?
– Lyth
Sep 18 '13 at 12:32
3
3
Check also this: stackoverflow.com/questions/6974684/…, here it explains how to achieve it via jQuery
– Chococroc
Jan 15 '14 at 12:09
Check also this: stackoverflow.com/questions/6974684/…, here it explains how to achieve it via jQuery
– Chococroc
Jan 15 '14 at 12:09
2
2
@Jimmy How would he get the get the file that lies in the input instead?
– alex
Dec 5 '14 at 18:05
@Jimmy How would he get the get the file that lies in the input instead?
– alex
Dec 5 '14 at 18:05
|
show 3 more comments
32 Answers
32
active
oldest
votes
1 2
next
up vote
2378
down vote
With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution.
The HTML:
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>
First, you can do some validation if you want. For example, in the onChange event of the file:
$(':file').on('change', function() {
var file = this.files[0];
if (file.size > 1024) {
alert('max upload size is 1k')
}
// Also see .name, .type
});
Now the Ajax submit with the button's click:
$(':button').on('click', function() {
$.ajax({
// Your server script to process the upload
url: 'upload.php',
type: 'POST',
// Form data
data: new FormData($('form')[0]),
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
} , false);
}
return myXhr;
}
});
});
As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with Google Chrome as some of the HTML5 components of the examples aren't available in every browser.
9
Can I then use $_FILES in the upload.php?
– Alessandro Cosentino
Nov 2 '12 at 13:41
69
This should work in Internet Explorer but only Version 10. (caniuse.com/xhr2)
– Samir
Jan 2 '13 at 16:33
129
Doesn't work in IE7-9
– KevinDeus
May 6 '13 at 21:39
18
Hi, I appreciate PHP is your language of choice... but I am wondering if you know if this also works in ASP.NET MVC? I am a .NET developer and I have tried to utilize your simple example to do some AJAX file uploading but server side I do not get the file I posted via AJAX. I am using latest Chrome.
– Shumii
Jun 1 '13 at 5:29
23
It's FormData who does all the magic here. Be sure to check these docs — it covers all your question about multiple files and fields.
– incarnate
Sep 12 '13 at 13:26
|
show 32 more comments
up vote
339
down vote
There are various ready-made plugins on doing file upload for jQuery.
Doing this kind of uploading hacks is not an enjoyable experience, so people enjoy using ready-made solutions.
Here's few:
- JQuery File Uploader
- Multiple File Upload Plugin
- Mini Multiple File Upload
- jQuery File Upload
You can search for more projects on NPM (using "jquery-plugin" as the keyword) or on Github.
14
The AjaxFUP-link seems to be broken. I suspect this is what is refered to: valums.com/ajax-upload
– UlfR
Jul 16 '09 at 6:31
1
For yet another read-made plugin, there's always Filepicker.io, which is kind of nice in that it deals with all of the nasty large file support issues, etc.
– brettcvz
Jun 21 '12 at 23:19
8
It's actually only about 10 lines of vanilla JS. It really isn't so bad.
– mpen
Feb 17 '13 at 9:30
3
Ready-made solution plugins may work great but it doesn't help after a while you find out it doesn't work you thought it would and you had to hack it with unfamiliar scripts. So, it goes both ways.
– fletchsod
Sep 2 '14 at 13:54
Can i useJQuery File Uploader
for multiple videos..? will it support..?
– Mr world wide
Feb 13 '17 at 11:45
add a comment |
up vote
244
down vote
2017 Update: It still depends on the browsers your demographic uses.
An important thing to understand with the "new" HTML5 file
API is that is wasn't supported until IE 10. If the specific market you're aiming at has a higher-than-average prepensity toward older versions of Windows, you might not have access to it.
Going into 2017, about 5% of browsers are one of IE 6, 7, 8 or 9. If you head into a big corporation (eg this is a B2B tool, or something you're delivering for training) that number can rocket. Just a few months ago —in 2016— I dealt with a company using IE8 on over 60% of their machines.
So before you do anything: check what browser your users use. If you don't, you'll learn a quick and painful lesson in why "works for me" isn't good enough in a deliverable to a client.
My answer from 2008 follows.
However, there are viable non-JS methods of file uploads. You can create an iframe on the page (that you hide with CSS) and then target your form to post to that iframe. The main page doesn't need to move.
It's a "real" post so it's not wholly interactive. If you need status you need something server-side to process that. This varies massively depending on your server. ASP.NET has nicer mechanisms. PHP plain fails, but you can use Perl or Apache modifications to get around it.
If you need multiple file-uploads, it's best to do each file one at a time (to overcome maximum file upload limits). Post the first form to the iframe, monitor its progress using the above and when it has finished, post the second form to the iframe, and so on.
Or use a Java/Flash solution. They're a lot more flexible in what they can do with their posts...
137
For the record it's now possible to do pure AJAX file uploads if the browser supports the File API - developer.mozilla.org/en/using_files_from_web_applications
– meleyal
Mar 25 '11 at 10:05
33
Unless you need IE9 support. caniuse.com/fileapi
– Oli
Feb 5 '14 at 2:45
iframe solution is pretty simple and easy to get working
– Matthew Lock
Apr 17 '15 at 0:45
this is quite an old answer, but it was a bit misleading.. IE supported XHR natively as far back as IE7, and supported it through ActiveX as far back as IE5. w3schools.com/ajax/ajax_xmlhttprequest_create.asp. The practical way of doing this was certainly targeting flash (shockwave) components, or rolling out a Flash/ActiveX (Silverlight) control. If you can originate a request and handle the response via javascript, it's ajax.. though, having said that, ajax is synonymous with xhr, but it doesn't itself describe the underline mechanism/components that delivers/exchanges the payload.
– Brett Caswell
Oct 29 '15 at 14:54
4
@BrettCaswell I wasn't saying that AJAX/XHR weren't possible, just that it wasn't possible to post a file up with them on old —but everliving— versions of IE. That was and remains completely true.
– Oli
Oct 29 '15 at 15:34
add a comment |
up vote
107
down vote
I recommend using the Fine Uploader plugin for this purpose. Your JavaScript
code would be:
$(document).ready(function() {
$("#uploadbutton").jsupload({
action: "addFile.do",
onComplete: function(response){
alert( "server response: " + response);
}
});
});
It uses JSON - so for PHP old version it will be non possible use.
– Lorenzo Manucci
Jun 22 '11 at 9:35
Seems much cleaner than Ajax File Upload, where I need to include a huge piece of code just to use the damn thing.
– ripper234
Dec 6 '11 at 14:52
5
URL is now valums.com/ajax-upload.
– Patrick Fisher
Feb 12 '12 at 2:07
34
"This plugin is open sourced under GNU GPL 2 or later and GNU LGPL 2 or later." So as long as you don't distribute the copy or a modified version, you don't have to open your project.
– Trantor Liu
Jul 23 '12 at 12:02
1
This is the website (fineuploader.com) I found now, it's V4.2 .
– Andrew_1510
Feb 5 '14 at 10:25
|
show 7 more comments
up vote
92
down vote
Note: This answer is outdated, it is now possible to upload files using XHR.
You cannot upload files using XMLHttpRequest (Ajax). You can simulate the effect using an iframe or Flash. The excellent jQuery Form Plugin that posts your files through an iframe to get the effect.
1
Yes, you can POST to an iframe and capture the file there. I have very limited experience with this though, so I can't really comment on it.
– Mattias
Oct 3 '08 at 17:21
15
Small remark: in latest versions of chrome and firefox it is possible, stackoverflow.com/questions/4856917/…
– Alleo
Nov 3 '11 at 18:57
Not supported in IE9 and less
– Radmation
Sep 7 at 20:43
add a comment |
up vote
82
down vote
This AJAX file upload jQuery plugin uploads the file somehwere, and passes the
response to a callback, nothing else.
- It does not depend on specific HTML, just give it a
<input type="file">
- It does not require your server to respond in any particular way
- It does not matter how many files you use, or where they are on the page
-- Use as little as --
$('#one-specific-file').ajaxfileupload({
'action': '/upload.php'
});
-- or as much as --
$('input[type="file"]').ajaxfileupload({
'action': '/upload.php',
'params': {
'extra': 'info'
},
'onComplete': function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
},
'onStart': function() {
if(weWantedTo) return false; // cancels upload
},
'onCancel': function() {
console.log('no file selected');
}
});
4
Not working with 1.9.1 :|
– user840250
Mar 24 '13 at 11:31
1
@user840250 jQuery 1.9.1?
– Jordan Feldstein
Mar 25 '13 at 17:33
add a comment |
up vote
81
down vote
Wrapping up for future readers.
Asynchronous File Upload
With HTML5
You can upload files with jQuery using the $.ajax()
method if FormData and the File API are supported (both HTML5 features).
You can also send files without FormData but either way the File API must be present to process files in such a way that they can be sent with XMLHttpRequest (Ajax).
$.ajax({
url: 'file/destination.html',
type: 'POST',
data: new FormData($('#formWithFiles')[0]), // The form with the file inputs.
processData: false,
contentType: false // Using FormData, no need to process data.
}).done(function(){
console.log("Success: Files sent!");
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
For a quick, pure JavaScript (no jQuery) example see "Sending files using a FormData object".
Fallback
When HTML5 isn't supported (no File API) the only other pure JavaScript solution (no Flash or any other browser plugin) is the hidden iframe technique, which allows to emulate an asynchronous request without using the XMLHttpRequest object.
It consists of setting an iframe as the target of the form with the file inputs. When the user submits a request is made and the files are uploaded but the response is displayed inside the iframe instead of re-rendering the main page. Hiding the iframe makes the whole process transparent to the user and emulates an asynchronous request.
If done properly it should work virtually on any browser, but it has some caveats as how to obtain the response from the iframe.
In this case you may prefer to use a wrapper plugin like Bifröst which uses the iframe technique but also provides a jQuery Ajax transport allowing to send files with just the $.ajax()
method like this:
$.ajax({
url: 'file/destination.html',
type: 'POST',
// Set the transport to use (iframe means to use Bifröst)
// and the expected data type (json in this case).
dataType: 'iframe json',
fileInputs: $('input[type="file"]'), // The file inputs containing the files to send.
data: { msg: 'Some extra data you might need.'}
}).done(function(){
console.log("Success: Files sent!");
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
Plugins
Bifröst is just a small wrapper that adds fallback support to jQuery's ajax method, but many of the aforementioned plugins like jQuery Form Plugin or jQuery File Upload include the whole stack from HTML5 to different fallbacks and some useful features to ease out the process. Depending on your needs and requirements you might want to consider a bare implementation or either of this plugins.
3
One thing to note, based on the documentation: you should also sendcontentType: false
. When I didn't send this with chrome the form content type was invalidated by jQuery.
– ash
Aug 18 '15 at 22:44
Nice answer. A few suggestions for improvement: Remove the parts of the code unrelated to the answer, for example the.done()
and.fail()
callbacks. Also, an example without the use ofFormData
and a list of pro/cons would be awesome.
– Zero3
Dec 19 '15 at 18:10
I got this error:TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
– candlejack
Dec 25 '16 at 23:15
add a comment |
up vote
58
down vote
I have been using the below script to upload images which happens to work fine.
HTML
<input id="file" type="file" name="file"/>
<div id="response"></div>
JavaScript
jQuery('document').ready(function(){
var input = document.getElementById("file");
var formdata = false;
if (window.FormData) {
formdata = new FormData();
}
input.addEventListener("change", function (evt) {
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
//showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("image", file);
formdata.append("extra",'extra-data');
}
if (formdata) {
jQuery('div#response').html('<br /><img src="ajax-loader.gif"/>');
jQuery.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
jQuery('div#response').html("Successfully uploaded");
}
});
}
}
else
{
alert('Not a vaild image!');
}
}
}, false);
});
Explanation
I use response div
to show the uploading animation and response after upload is done.
Best part is you can send extra data such as ids & etc with the file when you use this script. I have mention it extra-data
as in the script.
At the PHP level this will work as normal file upload. extra-data can be retrieved as $_POST
data.
Here you are not using a plugin and stuff. You can change the code as you want. You are not blindly coding here. This is the core functionality of any jQuery file upload. Actually Javascript.
5
-1 for using jQuery and not using it's selector engine and event handlers.addEventListener
is not cross-browser.
– Mark
Sep 22 '13 at 20:49
3
Because it would be pointless to add a separate answer which would be mostly based on this one, with just a few changes. Instead, this answer should be corrected.
– Mark
Nov 23 '13 at 16:14
2
@RainFromHeaven, please, can you edit the answer? I don't know how to do it in the cross-browser way.
– Thiago Negri
Jan 27 '14 at 13:57
2
Still does not work in IE 9 and down. Allot of users still use those versions of IE.
– Pierre
Jun 28 '14 at 10:48
1
Can someone please explain how can this be made to work in asp.net? Do I use webmethod? If yes what would it look like?
– Arbaaz
May 23 '15 at 5:23
add a comment |
up vote
56
down vote
I've come across a few really powerful jQuery-based file upload libraries. Check these out:
Plupload
- docs: http://www.plupload.com/docs
- docs: http://www.plupload.com/docs
jQuery File Upload
- docs: https://github.com/blueimp/jQuery-File-Upload
- docs: https://github.com/blueimp/jQuery-File-Upload
FineUploader
- docs: http://docs.fineuploader.com/
- docs: http://docs.fineuploader.com/
add a comment |
up vote
42
down vote
You can upload simply with jQuery .ajax()
.
HTML:
<form id="upload-form">
<div>
<label for="file">File:</label>
<input type="file" id="file" name="file" />
<progress class="progress" value="0" max="100"></progress>
</div>
<hr />
<input type="submit" value="Submit" />
</form>
CSS
.progress { display: none; }
Javascript:
$(document).ready(function(ev) {
$("#upload-form").on('submit', (function(ev) {
ev.preventDefault();
$.ajax({
xhr: function() {
var progress = $('.progress'),
xhr = $.ajaxSettings.xhr();
progress.show();
xhr.upload.onprogress = function(ev) {
if (ev.lengthComputable) {
var percentComplete = parseInt((ev.loaded / ev.total) * 100);
progress.val(percentComplete);
if (percentComplete === 100) {
progress.hide().val(0);
}
}
};
return xhr;
},
url: 'upload.php',
type: 'POST',
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data, status, xhr) {
// ...
},
error: function(xhr, status, error) {
// ...
}
});
}));
});
What jQuery library do I need t o run this code?
– Rayden Black
Dec 16 '15 at 2:32
1
@RaydenBlack only jQuery.
– Zayn Ali
Dec 18 '15 at 0:34
how to get upload progress?
– Ali Sherafat
Jul 22 '17 at 18:24
@AliSherafat i've updated my answer. try it
– Zayn Ali
Jul 23 '17 at 0:53
add a comment |
up vote
41
down vote
You can do it in vanilla JavaScript pretty easily. Here's a snippet from my current project:
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
var percent = (e.position/ e.totalSize);
// Render a pretty progress bar
};
xhr.onreadystatechange = function(e) {
if(this.readyState === 4) {
// Handle file upload complete
}
};
xhr.open('POST', '/upload', true);
xhr.setRequestHeader('X-FileName',file.name); // Pass the filename along
xhr.send(file);
3
@Gary: Sorry, I should have posted that bit too. I was just using the new drag-and-drop functionality in HTML5; you can find an example here: html5demos.com/file-api#view-source -- just click "view source". Essentially, inside theondrop
event you can dovar file = e.dataTransfer.files[0]
– mpen
Apr 3 '13 at 15:35
Perhaps the question has been edited since, but some people on a let's discussion I opened think a vanilla JS answer is off topic if OP asks for a jQuery solution (provided one exists) and such answers belong with a separate question.
– Andy
Oct 31 '17 at 6:55
2
@Andy Well I disagree, and it seems 34 others do too. If you can use jQuery, then you can certainly use JavaScript. In any case, this is a community site -- it's not just OP that I'm trying to help here. Everyone is free to choose/use the answer they like best. Some people just gravitate towards jQuery because they think it'll be so much easier/fewer lines of code, when really they don't need the overhead of an extra library at all.
– mpen
Oct 31 '17 at 16:20
add a comment |
up vote
38
down vote
The simplest and most robust way I have done this in the past, is to simply target a hidden iFrame tag with your form - then it will submit within the iframe without reloading the page.
That is if you don't want to use a plugin, JavaScript or any other forms of "magic" other than HTML. Of course you can combine this with JavaScript or what have you...
<form target="iframe" action="" method="post" enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<iframe name="iframe" id="iframe" style="display:none" ></iframe>
You can also read the contents of the iframe onLoad
for server errors or success responses and then output that to user.
Chrome, iFrames, and onLoad
-note- you only need to keep reading if you are interested in how to setup a UI blocker when doing uploading/downloading
Currently Chrome doesn't trigger the onLoad event for the iframe when it's used to transfer files. Firefox, IE, and Edge all fire the onload event for file transfers.
The only solution that I found works for Chrome was to use a cookie.
To do that basically when the upload/download is started:
- [Client Side] Start an interval to look for the existence of a cookie
- [Server Side] Do whatever you need to with the file data
- [Server Side] Set cookie for client side interval
- [Client Side] Interval sees the cookie and uses it like the onLoad event. For example you can start a UI blocker and then onLoad ( or when cookie is made ) you remove the UI blocker.
Using a cookie for this is ugly but it works.
I made a jQuery plugin to handle this issue for Chrome when downloading, you can find here
https://github.com/ArtisticPhoenix/jQuery-Plugins/blob/master/iDownloader.js
The same basic principal applies to uploading, as well.
To use the downloader ( include the JS, obviously )
$('body').iDownloader({
"onComplete" : function(){
$('#uiBlocker').css('display', 'none'); //hide ui blocker on complete
}
});
$('somebuttion').click( function(){
$('#uiBlocker').css('display', 'block'); //block the UI
$('body').iDownloader('download', 'htttp://example.com/location/of/download');
});
And on the server side, just before transferring the file data, create the cookie
setcookie('iDownloader', true, time() + 30, "/");
The plugin will see the cookie, and then trigger the onComplete
callback.
3
I love it. If only someone could mention the potential problems with this brilliant solution. I really don't understand why people wright and use these clunky libraries and plugins when there is the solution.
– Yevgeniy Afanasyev
Jan 5 '15 at 22:45
1
Well, I guess the reason would be to show some progress info while uploading.
– Prakhar Mishra
Jun 28 '16 at 11:19
add a comment |
up vote
31
down vote
A solution I found was to have the <form>
target a hidden iFrame. The iFrame can then run JS to display to the user that it's complete (on page load).
This is what jQuery Form does: malsup.com/jquery/form
– Darryl Hein
Sep 15 '14 at 16:59
1
i am interested in this answer, do you have a demo you can link to?
– lfender6445
Jan 30 '15 at 6:37
add a comment |
up vote
30
down vote
I've written this up in a Rails environment. It's only about five lines of JavaScript, if you use the lightweight jQuery-form plugin.
The challenge is in getting AJAX upload working as the standard remote_form_for
doesn't understand multi-part form submission. It's not going to send the file data Rails seeks back with the AJAX request.
That's where the jQuery-form plugin comes into play.
Here’s the Rails code for it:
<% remote_form_for(:image_form,
:url => { :controller => "blogs", :action => :create_asset },
:html => { :method => :post,
:id => 'uploadForm', :multipart => true })
do |f| %>
Upload a file: <%= f.file_field :uploaded_data %>
<% end %>
Here’s the associated JavaScript:
$('#uploadForm input').change(function(){
$(this).parent().ajaxSubmit({
beforeSubmit: function(a,f,o) {
o.dataType = 'json';
},
complete: function(XMLHttpRequest, textStatus) {
// XMLHttpRequest.responseText will contain the URL of the uploaded image.
// Put it in an image element you create, or do with it what you will.
// For example, if you have an image elemtn with id "my_image", then
// $('#my_image').attr('src', XMLHttpRequest.responseText);
// Will set that image tag to display the uploaded image.
},
});
});
And here’s the Rails controller action, pretty vanilla:
@image = Image.new(params[:image_form])
@image.save
render :text => @image.public_filename
I’ve been using this for the past few weeks with Bloggity, and it’s worked like a champ.
add a comment |
up vote
29
down vote
Simple Ajax Uploader is another option:
https://github.com/LPology/Simple-Ajax-Uploader
- Cross-browser -- works in IE7+, Firefox, Chrome, Safari, Opera
- Supports multiple, concurrent uploads -- even in non-HTML5 browsers
- No flash or external CSS -- just one 5Kb Javascript file
- Optional, built-in support for fully cross-browser progress bars (using PHP's APC extension)
- Flexible and highly customizable -- use any element as upload button, style your own progress indicators
- No forms required, just provide an element that will serve as upload button
- MIT license -- free to use in commercial project
Example usage:
var uploader = new ss.SimpleUpload({
button: $('#uploadBtn'), // upload button
url: '/uploadhandler', // URL of server-side upload handler
name: 'userfile', // parameter name of the uploaded file
onSubmit: function() {
this.setProgressBar( $('#progressBar') ); // designate elem as our progress bar
},
onComplete: function(file, response) {
// do whatever after upload is finished
}
});
2
This seems to be the most promising so far, You had me atIE7+
! Trying it out now. Thanks
– Pierre
Jun 28 '14 at 10:53
add a comment |
up vote
21
down vote
jQuery Uploadify is another good plugin which I have used before to upload files. The JavaScript code is as simple as the following: code. However, the new version does not work in Internet Explorer.
$('#file_upload').uploadify({
'swf': '/public/js/uploadify.swf',
'uploader': '/Upload.ashx?formGuid=' + $('#formGuid').val(),
'cancelImg': '/public/images/uploadify-cancel.png',
'multi': true,
'onQueueComplete': function (queueData) {
// ...
},
'onUploadStart': function (file) {
// ...
}
});
I have done a lot of searching and I have come to another solution for uploading files without any plugin and only with ajax. The solution is as below:
$(document).ready(function () {
$('#btn_Upload').live('click', AjaxFileUpload);
});
function AjaxFileUpload() {
var fileInput = document.getElementById("#Uploader");
var file = fileInput.files[0];
var fd = new FormData();
fd.append("files", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", 'Uploader.ashx');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert('success');
}
else if (uploadResult == 'success')
alert('error');
};
xhr.send(fd);
}
2
Uploadify has been dead for years. Not supported or maintained anymore.
– Ray Nicholus
Jun 8 '16 at 17:44
add a comment |
up vote
20
down vote
Here's just another solution of how to upload file (without any plugin)
Using simple Javascripts and AJAX (with progress-bar)
HTML part
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
JS part
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
PHP part
<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){ // assuming the directory name 'test_uploads'
echo "$fileName upload is complete";
} else {
echo "move_uploaded_file function failed";
}
?>
Here's the EXAMPLE application
Does not work with IE9.
– Zameer Fouzan
Jan 31 at 14:16
add a comment |
up vote
15
down vote
var formData=new FormData();
formData.append("fieldname","value");
formData.append("image",$('[name="filename"]')[0].files[0]);
$.ajax({
url:"page.php",
data:formData,
type: 'POST',
dataType:"JSON",
cache: false,
contentType: false,
processData: false,
success:function(data){ }
});
You can use form data to post all your values including images.
6
Note:cache: false
is redundant on aPOST
request asPOST
never caches.
– Gone Coding
Aug 10 '15 at 9:10
@Vivek Aasaithambi, I got this error:TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
– candlejack
Dec 25 '16 at 23:28
add a comment |
up vote
12
down vote
To upload file asynchronously with Jquery use below steps:
step 1 In your project open Nuget manager and add package (jquery fileupload(only you need to write it in search box it will come up and install it.))
URL: https://github.com/blueimp/jQuery-File-Upload
step 2 Add below scripts in the HTML files, which are already added to the project by running above package:
jquery.ui.widget.js
jquery.iframe-transport.js
jquery.fileupload.js
step 3 Write file upload control as per below code:
<input id="upload" name="upload" type="file" />
step 4 write a js method as uploadFile as below:
function uploadFile(element) {
$(element).fileupload({
dataType: 'json',
url: '../DocumentUpload/upload',
autoUpload: true,
add: function (e, data) {
// write code for implementing, while selecting a file.
// data represents the file data.
//below code triggers the action in mvc controller
data.formData =
{
files: data.files[0]
};
data.submit();
},
done: function (e, data) {
// after file uploaded
},
progress: function (e, data) {
// progress
},
fail: function (e, data) {
//fail operation
},
stop: function () {
code for cancel operation
}
});
};
step 5 In ready function call element file upload to initiate the process as per below:
$(document).ready(function()
{
uploadFile($('#upload'));
});
step 6 Write MVC controller and Action as per below:
public class DocumentUploadController : Controller
{
[System.Web.Mvc.HttpPost]
public JsonResult upload(ICollection<HttpPostedFileBase> files)
{
bool result = false;
if (files != null || files.Count > 0)
{
try
{
foreach (HttpPostedFileBase file in files)
{
if (file.ContentLength == 0)
throw new Exception("Zero length file!");
else
//code for saving a file
}
}
catch (Exception)
{
result = false;
}
}
return new JsonResult()
{
Data=result
};
}
}
add a comment |
up vote
8
down vote
Convert file to base64 using |HTML5's readAsDataURL() or some base64 encoder.
Fiddle here
var reader = new FileReader();
reader.onload = function(readerEvt) {
var binaryString = readerEvt.target.result;
document.getElementById("base64textarea").value = btoa(binaryString);
};
reader.readAsBinaryString(file);
Then to retrieve:
window.open("data:application/octet-stream;base64," + base64);
add a comment |
up vote
8
down vote
You can see a solved solution with a working demo here that allows you to preview and submit form files to the server. For your case, you need to use Ajax to facilitate the file upload to the server:
<from action="" id="formContent" method="post" enctype="multipart/form-data">
<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>
</form>
The data being submitted is a formdata. On your jQuery, use a form submit function instead of a button click to submit the form file as shown below.
$(document).ready(function () {
$("#formContent").submit(function(e){
e.preventDefault();
var formdata = new FormData(this);
$.ajax({
url: "ajax_upload_image.php",
type: "POST",
data: formdata,
mimeTypes:"multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(){
alert("successfully submitted");
});
});
});
View more details
add a comment |
up vote
8
down vote
Sample: If you use jQuery, you can do easy to an upload file. This is a small and strong jQuery plugin, http://jquery.malsup.com/form/.
Example
var $bar = $('.ProgressBar');
$('.Form').ajaxForm({
dataType: 'json',
beforeSend: function(xhr) {
var percentVal = '0%';
$bar.width(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
$bar.width(percentVal)
},
success: function(response) {
// Response
}
});
I hope it would be helpful
add a comment |
up vote
7
down vote
You can use
$(function() {
$("#file_upload_1").uploadify({
height : 30,
swf : '/uploadify/uploadify.swf',
uploader : '/uploadify/uploadify.php',
width : 120
});
});
Demo
add a comment |
up vote
7
down vote
A modern approach without Jquery is to use the FileList object you get back from <input type="file">
when user selects a file(s) and then use Fetch to post the FileList wrapped around a FormData object.
// The input DOM element
const inputElement = document.querySelector('input');
// Listen for a file submit from user
inputElement.addEventListener('change', () => {
const data = new FormData();
data.append('file', inputElement.files[0]);
data.append('imageName', 'flower');
// Post to server
fetch('/uploadImage', {
method: 'POST',
body: data
});
});
add a comment |
up vote
5
down vote
Look for Handling the upload process for a file, asynchronously in here:
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
Sample from the link
<?php
if (isset($_FILES['myFile'])) {
// Example:
move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']);
exit;
}
?><!DOCTYPE html>
<html>
<head>
<title>dnd binary upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function sendFile(file) {
var uri = "/index.php";
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", uri, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Handle response.
alert(xhr.responseText); // handle response.
}
};
fd.append('myFile', file);
// Initiate a multipart/form-data upload
xhr.send(fd);
}
window.onload = function() {
var dropzone = document.getElementById("dropzone");
dropzone.ondragover = dropzone.ondragenter = function(event) {
event.stopPropagation();
event.preventDefault();
}
dropzone.ondrop = function(event) {
event.stopPropagation();
event.preventDefault();
var filesArray = event.dataTransfer.files;
for (var i=0; i<filesArray.length; i++) {
sendFile(filesArray[i]);
}
}
}
</script>
</head>
<body>
<div>
<div id="dropzone" style="margin:30px; width:500px; height:300px; border:1px dotted grey;">Drag & drop your file here...</div>
</div>
</body>
</html>
add a comment |
up vote
5
down vote
You can pass additional parameters along with file name on making asynchronous upload using XMLHttpRequest (without flash and iframe dependency). Append the additional parameter value with FormData and send the upload request.
var formData = new FormData();
formData.append('parameter1', 'value1');
formData.append('parameter2', 'value2');
formData.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'post back url',
data: formData,
// other attributes of AJAX
});
Also, Syncfusion JavaScript UI file upload provides solution for this scenario simply using event argument. you can find documentation here and further details about this control here enter link description here
add a comment |
up vote
4
down vote
This is my solution.
<form enctype="multipart/form-data">
<div class="form-group">
<label class="control-label col-md-2" for="apta_Description">Description</label>
<div class="col-md-10">
<input class="form-control text-box single-line" id="apta_Description" name="apta_Description" type="text" value="">
</div>
</div>
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
and the js
<script>
$(':button').click(function () {
var formData = new FormData($('form')[0]);
$.ajax({
url: '@Url.Action("Save", "Home")',
type: 'POST',
success: completeHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
});
function completeHandler() {
alert(":)");
}
</script>
Controller
[HttpPost]
public ActionResult Save(string apta_Description, HttpPostedFileBase file)
{
return Json(":)");
}
1
You seem to have mixed some kind of framework into your answer. You should, at the very least, mention which framework your answer is usable for. Better yet, remove all the framework stuff and present only an answer to the question posed.
– Zero3
Dec 19 '15 at 18:06
2
so there's actually a mvc framework called "mvc"? and it uses csharpish syntax? that's cruel.
– nonchip
Jan 6 '16 at 22:27
add a comment |
up vote
3
down vote
Using HTML5 and JavaScript, uploading async is quite easy, I create the uploading logic along with your html, this is not fully working as it needs the api, but demonstrate how it works, if you have the endpoint called /upload
from root of your website, this code should work for you:
const asyncFileUpload = () => {
const fileInput = document.getElementById("file");
const file = fileInput.files[0];
const uri = "/upload";
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = e => {
const percentage = e.loaded / e.total;
console.log(percentage);
};
xhr.onreadystatechange = e => {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("file uploaded");
}
};
xhr.open("POST", uri, true);
xhr.setRequestHeader("X-FileName", file.name);
xhr.send(file);
}
<form>
<span>File</span>
<input type="file" id="file" name="file" size="10" />
<input onclick="asyncFileUpload()" id="upload" type="button" value="Upload" />
</form>
Also some further information about XMLHttpReques:
The XMLHttpRequest Object
All modern browsers support the XMLHttpRequest object.
The XMLHttpRequest object can be used to exchange data with a web
server behind the scenes. This means that it is possible to update
parts of a web page, without reloading the whole page.
Create an XMLHttpRequest Object
All modern browsers (Chrome, Firefox,
IE7+, Edge, Safari, Opera) have a built-in XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
variable = new XMLHttpRequest();
Access Across Domains
For security reasons, modern browsers do not
allow access across domains.
This means that both the web page and the XML file it tries to load,
must be located on the same server.
The examples on W3Schools all open XML files located on the W3Schools
domain.
If you want to use the example above on one of your own web pages, the
XML files you load must be located on your own server.
For more details, you can continue reading here...
add a comment |
up vote
2
down vote
You can use newer Fetch API by JavaScript. Like this:
function uploadButtonCLicked(){
var input = document.querySelector('input[type="file"]')
fetch('/url', {
method: 'POST',
body: input.files[0]
}).then(res => res.json()) // you can do something with response
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
Advantage: Fetch API is natively supported by all modern browsers, so you don't have to import anything. Also, note that fetch() returns a Promise which is then handled by using .then(..code to handle response..)
asynchronously.
add a comment |
up vote
2
down vote
You can do the Asynchronous Multiple File uploads using JavaScript or jQuery and that to without using any plugin. You can also show the real time progress of file upload in the progress control. I have come across 2 nice links -
- ASP.NET Web Forms based Mulitple File Upload Feature with Progress Bar
- ASP.NET MVC based Multiple File Upload made in jQuery
The server side language is C# but you can do some modification for making it work with other language like PHP.
File Upload ASP.NET Core MVC:
In the View create file upload control in html:
<form method="post" asp-action="Add" enctype="multipart/form-data">
<input type="file" multiple name="mediaUpload" />
<button type="submit">Submit</button>
</form>
Now create action method in your controller:
[HttpPost]
public async Task<IActionResult> Add(IFormFile mediaUpload)
{
//looping through all the files
foreach (IFormFile file in mediaUpload)
{
//saving the files
string path = Path.Combine(hostingEnvironment.WebRootPath, "some-folder-path");
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
}
hostingEnvironment variable is of type IHostingEnvironment which can be injected to the controller using dependency injection, like:
private IHostingEnvironment hostingEnvironment;
public MediaController(IHostingEnvironment environment)
{
hostingEnvironment = environment;
}
Could you include the essence of the solution in your answer, as it otherwise might become useless if the linked website changes or goes offline.
– Dima Kozhevin
Aug 29 at 20:12
add a comment |
1 2
next
protected by Will Aug 30 '10 at 11:41
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
32 Answers
32
active
oldest
votes
32 Answers
32
active
oldest
votes
active
oldest
votes
active
oldest
votes
1 2
next
up vote
2378
down vote
With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution.
The HTML:
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>
First, you can do some validation if you want. For example, in the onChange event of the file:
$(':file').on('change', function() {
var file = this.files[0];
if (file.size > 1024) {
alert('max upload size is 1k')
}
// Also see .name, .type
});
Now the Ajax submit with the button's click:
$(':button').on('click', function() {
$.ajax({
// Your server script to process the upload
url: 'upload.php',
type: 'POST',
// Form data
data: new FormData($('form')[0]),
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
} , false);
}
return myXhr;
}
});
});
As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with Google Chrome as some of the HTML5 components of the examples aren't available in every browser.
9
Can I then use $_FILES in the upload.php?
– Alessandro Cosentino
Nov 2 '12 at 13:41
69
This should work in Internet Explorer but only Version 10. (caniuse.com/xhr2)
– Samir
Jan 2 '13 at 16:33
129
Doesn't work in IE7-9
– KevinDeus
May 6 '13 at 21:39
18
Hi, I appreciate PHP is your language of choice... but I am wondering if you know if this also works in ASP.NET MVC? I am a .NET developer and I have tried to utilize your simple example to do some AJAX file uploading but server side I do not get the file I posted via AJAX. I am using latest Chrome.
– Shumii
Jun 1 '13 at 5:29
23
It's FormData who does all the magic here. Be sure to check these docs — it covers all your question about multiple files and fields.
– incarnate
Sep 12 '13 at 13:26
|
show 32 more comments
up vote
2378
down vote
With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution.
The HTML:
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>
First, you can do some validation if you want. For example, in the onChange event of the file:
$(':file').on('change', function() {
var file = this.files[0];
if (file.size > 1024) {
alert('max upload size is 1k')
}
// Also see .name, .type
});
Now the Ajax submit with the button's click:
$(':button').on('click', function() {
$.ajax({
// Your server script to process the upload
url: 'upload.php',
type: 'POST',
// Form data
data: new FormData($('form')[0]),
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
} , false);
}
return myXhr;
}
});
});
As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with Google Chrome as some of the HTML5 components of the examples aren't available in every browser.
9
Can I then use $_FILES in the upload.php?
– Alessandro Cosentino
Nov 2 '12 at 13:41
69
This should work in Internet Explorer but only Version 10. (caniuse.com/xhr2)
– Samir
Jan 2 '13 at 16:33
129
Doesn't work in IE7-9
– KevinDeus
May 6 '13 at 21:39
18
Hi, I appreciate PHP is your language of choice... but I am wondering if you know if this also works in ASP.NET MVC? I am a .NET developer and I have tried to utilize your simple example to do some AJAX file uploading but server side I do not get the file I posted via AJAX. I am using latest Chrome.
– Shumii
Jun 1 '13 at 5:29
23
It's FormData who does all the magic here. Be sure to check these docs — it covers all your question about multiple files and fields.
– incarnate
Sep 12 '13 at 13:26
|
show 32 more comments
up vote
2378
down vote
up vote
2378
down vote
With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution.
The HTML:
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>
First, you can do some validation if you want. For example, in the onChange event of the file:
$(':file').on('change', function() {
var file = this.files[0];
if (file.size > 1024) {
alert('max upload size is 1k')
}
// Also see .name, .type
});
Now the Ajax submit with the button's click:
$(':button').on('click', function() {
$.ajax({
// Your server script to process the upload
url: 'upload.php',
type: 'POST',
// Form data
data: new FormData($('form')[0]),
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
} , false);
}
return myXhr;
}
});
});
As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with Google Chrome as some of the HTML5 components of the examples aren't available in every browser.
With HTML5 you can make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME type) or handle the progress event with the HTML5 progress tag (or a div). Recently I had to make a file uploader, but I didn't want to use Flash nor Iframes or plugins and after some research I came up with the solution.
The HTML:
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>
First, you can do some validation if you want. For example, in the onChange event of the file:
$(':file').on('change', function() {
var file = this.files[0];
if (file.size > 1024) {
alert('max upload size is 1k')
}
// Also see .name, .type
});
Now the Ajax submit with the button's click:
$(':button').on('click', function() {
$.ajax({
// Your server script to process the upload
url: 'upload.php',
type: 'POST',
// Form data
data: new FormData($('form')[0]),
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
} , false);
}
return myXhr;
}
});
});
As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with Google Chrome as some of the HTML5 components of the examples aren't available in every browser.
edited Mar 20 at 6:51
Ayush Gupta
3,0011641
3,0011641
answered Jan 6 '12 at 13:34
olanod
25.4k63361
25.4k63361
9
Can I then use $_FILES in the upload.php?
– Alessandro Cosentino
Nov 2 '12 at 13:41
69
This should work in Internet Explorer but only Version 10. (caniuse.com/xhr2)
– Samir
Jan 2 '13 at 16:33
129
Doesn't work in IE7-9
– KevinDeus
May 6 '13 at 21:39
18
Hi, I appreciate PHP is your language of choice... but I am wondering if you know if this also works in ASP.NET MVC? I am a .NET developer and I have tried to utilize your simple example to do some AJAX file uploading but server side I do not get the file I posted via AJAX. I am using latest Chrome.
– Shumii
Jun 1 '13 at 5:29
23
It's FormData who does all the magic here. Be sure to check these docs — it covers all your question about multiple files and fields.
– incarnate
Sep 12 '13 at 13:26
|
show 32 more comments
9
Can I then use $_FILES in the upload.php?
– Alessandro Cosentino
Nov 2 '12 at 13:41
69
This should work in Internet Explorer but only Version 10. (caniuse.com/xhr2)
– Samir
Jan 2 '13 at 16:33
129
Doesn't work in IE7-9
– KevinDeus
May 6 '13 at 21:39
18
Hi, I appreciate PHP is your language of choice... but I am wondering if you know if this also works in ASP.NET MVC? I am a .NET developer and I have tried to utilize your simple example to do some AJAX file uploading but server side I do not get the file I posted via AJAX. I am using latest Chrome.
– Shumii
Jun 1 '13 at 5:29
23
It's FormData who does all the magic here. Be sure to check these docs — it covers all your question about multiple files and fields.
– incarnate
Sep 12 '13 at 13:26
9
9
Can I then use $_FILES in the upload.php?
– Alessandro Cosentino
Nov 2 '12 at 13:41
Can I then use $_FILES in the upload.php?
– Alessandro Cosentino
Nov 2 '12 at 13:41
69
69
This should work in Internet Explorer but only Version 10. (caniuse.com/xhr2)
– Samir
Jan 2 '13 at 16:33
This should work in Internet Explorer but only Version 10. (caniuse.com/xhr2)
– Samir
Jan 2 '13 at 16:33
129
129
Doesn't work in IE7-9
– KevinDeus
May 6 '13 at 21:39
Doesn't work in IE7-9
– KevinDeus
May 6 '13 at 21:39
18
18
Hi, I appreciate PHP is your language of choice... but I am wondering if you know if this also works in ASP.NET MVC? I am a .NET developer and I have tried to utilize your simple example to do some AJAX file uploading but server side I do not get the file I posted via AJAX. I am using latest Chrome.
– Shumii
Jun 1 '13 at 5:29
Hi, I appreciate PHP is your language of choice... but I am wondering if you know if this also works in ASP.NET MVC? I am a .NET developer and I have tried to utilize your simple example to do some AJAX file uploading but server side I do not get the file I posted via AJAX. I am using latest Chrome.
– Shumii
Jun 1 '13 at 5:29
23
23
It's FormData who does all the magic here. Be sure to check these docs — it covers all your question about multiple files and fields.
– incarnate
Sep 12 '13 at 13:26
It's FormData who does all the magic here. Be sure to check these docs — it covers all your question about multiple files and fields.
– incarnate
Sep 12 '13 at 13:26
|
show 32 more comments
up vote
339
down vote
There are various ready-made plugins on doing file upload for jQuery.
Doing this kind of uploading hacks is not an enjoyable experience, so people enjoy using ready-made solutions.
Here's few:
- JQuery File Uploader
- Multiple File Upload Plugin
- Mini Multiple File Upload
- jQuery File Upload
You can search for more projects on NPM (using "jquery-plugin" as the keyword) or on Github.
14
The AjaxFUP-link seems to be broken. I suspect this is what is refered to: valums.com/ajax-upload
– UlfR
Jul 16 '09 at 6:31
1
For yet another read-made plugin, there's always Filepicker.io, which is kind of nice in that it deals with all of the nasty large file support issues, etc.
– brettcvz
Jun 21 '12 at 23:19
8
It's actually only about 10 lines of vanilla JS. It really isn't so bad.
– mpen
Feb 17 '13 at 9:30
3
Ready-made solution plugins may work great but it doesn't help after a while you find out it doesn't work you thought it would and you had to hack it with unfamiliar scripts. So, it goes both ways.
– fletchsod
Sep 2 '14 at 13:54
Can i useJQuery File Uploader
for multiple videos..? will it support..?
– Mr world wide
Feb 13 '17 at 11:45
add a comment |
up vote
339
down vote
There are various ready-made plugins on doing file upload for jQuery.
Doing this kind of uploading hacks is not an enjoyable experience, so people enjoy using ready-made solutions.
Here's few:
- JQuery File Uploader
- Multiple File Upload Plugin
- Mini Multiple File Upload
- jQuery File Upload
You can search for more projects on NPM (using "jquery-plugin" as the keyword) or on Github.
14
The AjaxFUP-link seems to be broken. I suspect this is what is refered to: valums.com/ajax-upload
– UlfR
Jul 16 '09 at 6:31
1
For yet another read-made plugin, there's always Filepicker.io, which is kind of nice in that it deals with all of the nasty large file support issues, etc.
– brettcvz
Jun 21 '12 at 23:19
8
It's actually only about 10 lines of vanilla JS. It really isn't so bad.
– mpen
Feb 17 '13 at 9:30
3
Ready-made solution plugins may work great but it doesn't help after a while you find out it doesn't work you thought it would and you had to hack it with unfamiliar scripts. So, it goes both ways.
– fletchsod
Sep 2 '14 at 13:54
Can i useJQuery File Uploader
for multiple videos..? will it support..?
– Mr world wide
Feb 13 '17 at 11:45
add a comment |
up vote
339
down vote
up vote
339
down vote
There are various ready-made plugins on doing file upload for jQuery.
Doing this kind of uploading hacks is not an enjoyable experience, so people enjoy using ready-made solutions.
Here's few:
- JQuery File Uploader
- Multiple File Upload Plugin
- Mini Multiple File Upload
- jQuery File Upload
You can search for more projects on NPM (using "jquery-plugin" as the keyword) or on Github.
There are various ready-made plugins on doing file upload for jQuery.
Doing this kind of uploading hacks is not an enjoyable experience, so people enjoy using ready-made solutions.
Here's few:
- JQuery File Uploader
- Multiple File Upload Plugin
- Mini Multiple File Upload
- jQuery File Upload
You can search for more projects on NPM (using "jquery-plugin" as the keyword) or on Github.
edited Aug 26 '15 at 19:39
Esteban Herrera
1,64511227
1,64511227
answered Oct 15 '08 at 10:35
Cheery
12.4k115175
12.4k115175
14
The AjaxFUP-link seems to be broken. I suspect this is what is refered to: valums.com/ajax-upload
– UlfR
Jul 16 '09 at 6:31
1
For yet another read-made plugin, there's always Filepicker.io, which is kind of nice in that it deals with all of the nasty large file support issues, etc.
– brettcvz
Jun 21 '12 at 23:19
8
It's actually only about 10 lines of vanilla JS. It really isn't so bad.
– mpen
Feb 17 '13 at 9:30
3
Ready-made solution plugins may work great but it doesn't help after a while you find out it doesn't work you thought it would and you had to hack it with unfamiliar scripts. So, it goes both ways.
– fletchsod
Sep 2 '14 at 13:54
Can i useJQuery File Uploader
for multiple videos..? will it support..?
– Mr world wide
Feb 13 '17 at 11:45
add a comment |
14
The AjaxFUP-link seems to be broken. I suspect this is what is refered to: valums.com/ajax-upload
– UlfR
Jul 16 '09 at 6:31
1
For yet another read-made plugin, there's always Filepicker.io, which is kind of nice in that it deals with all of the nasty large file support issues, etc.
– brettcvz
Jun 21 '12 at 23:19
8
It's actually only about 10 lines of vanilla JS. It really isn't so bad.
– mpen
Feb 17 '13 at 9:30
3
Ready-made solution plugins may work great but it doesn't help after a while you find out it doesn't work you thought it would and you had to hack it with unfamiliar scripts. So, it goes both ways.
– fletchsod
Sep 2 '14 at 13:54
Can i useJQuery File Uploader
for multiple videos..? will it support..?
– Mr world wide
Feb 13 '17 at 11:45
14
14
The AjaxFUP-link seems to be broken. I suspect this is what is refered to: valums.com/ajax-upload
– UlfR
Jul 16 '09 at 6:31
The AjaxFUP-link seems to be broken. I suspect this is what is refered to: valums.com/ajax-upload
– UlfR
Jul 16 '09 at 6:31
1
1
For yet another read-made plugin, there's always Filepicker.io, which is kind of nice in that it deals with all of the nasty large file support issues, etc.
– brettcvz
Jun 21 '12 at 23:19
For yet another read-made plugin, there's always Filepicker.io, which is kind of nice in that it deals with all of the nasty large file support issues, etc.
– brettcvz
Jun 21 '12 at 23:19
8
8
It's actually only about 10 lines of vanilla JS. It really isn't so bad.
– mpen
Feb 17 '13 at 9:30
It's actually only about 10 lines of vanilla JS. It really isn't so bad.
– mpen
Feb 17 '13 at 9:30
3
3
Ready-made solution plugins may work great but it doesn't help after a while you find out it doesn't work you thought it would and you had to hack it with unfamiliar scripts. So, it goes both ways.
– fletchsod
Sep 2 '14 at 13:54
Ready-made solution plugins may work great but it doesn't help after a while you find out it doesn't work you thought it would and you had to hack it with unfamiliar scripts. So, it goes both ways.
– fletchsod
Sep 2 '14 at 13:54
Can i use
JQuery File Uploader
for multiple videos..? will it support..?– Mr world wide
Feb 13 '17 at 11:45
Can i use
JQuery File Uploader
for multiple videos..? will it support..?– Mr world wide
Feb 13 '17 at 11:45
add a comment |
up vote
244
down vote
2017 Update: It still depends on the browsers your demographic uses.
An important thing to understand with the "new" HTML5 file
API is that is wasn't supported until IE 10. If the specific market you're aiming at has a higher-than-average prepensity toward older versions of Windows, you might not have access to it.
Going into 2017, about 5% of browsers are one of IE 6, 7, 8 or 9. If you head into a big corporation (eg this is a B2B tool, or something you're delivering for training) that number can rocket. Just a few months ago —in 2016— I dealt with a company using IE8 on over 60% of their machines.
So before you do anything: check what browser your users use. If you don't, you'll learn a quick and painful lesson in why "works for me" isn't good enough in a deliverable to a client.
My answer from 2008 follows.
However, there are viable non-JS methods of file uploads. You can create an iframe on the page (that you hide with CSS) and then target your form to post to that iframe. The main page doesn't need to move.
It's a "real" post so it's not wholly interactive. If you need status you need something server-side to process that. This varies massively depending on your server. ASP.NET has nicer mechanisms. PHP plain fails, but you can use Perl or Apache modifications to get around it.
If you need multiple file-uploads, it's best to do each file one at a time (to overcome maximum file upload limits). Post the first form to the iframe, monitor its progress using the above and when it has finished, post the second form to the iframe, and so on.
Or use a Java/Flash solution. They're a lot more flexible in what they can do with their posts...
137
For the record it's now possible to do pure AJAX file uploads if the browser supports the File API - developer.mozilla.org/en/using_files_from_web_applications
– meleyal
Mar 25 '11 at 10:05
33
Unless you need IE9 support. caniuse.com/fileapi
– Oli
Feb 5 '14 at 2:45
iframe solution is pretty simple and easy to get working
– Matthew Lock
Apr 17 '15 at 0:45
this is quite an old answer, but it was a bit misleading.. IE supported XHR natively as far back as IE7, and supported it through ActiveX as far back as IE5. w3schools.com/ajax/ajax_xmlhttprequest_create.asp. The practical way of doing this was certainly targeting flash (shockwave) components, or rolling out a Flash/ActiveX (Silverlight) control. If you can originate a request and handle the response via javascript, it's ajax.. though, having said that, ajax is synonymous with xhr, but it doesn't itself describe the underline mechanism/components that delivers/exchanges the payload.
– Brett Caswell
Oct 29 '15 at 14:54
4
@BrettCaswell I wasn't saying that AJAX/XHR weren't possible, just that it wasn't possible to post a file up with them on old —but everliving— versions of IE. That was and remains completely true.
– Oli
Oct 29 '15 at 15:34
add a comment |
up vote
244
down vote
2017 Update: It still depends on the browsers your demographic uses.
An important thing to understand with the "new" HTML5 file
API is that is wasn't supported until IE 10. If the specific market you're aiming at has a higher-than-average prepensity toward older versions of Windows, you might not have access to it.
Going into 2017, about 5% of browsers are one of IE 6, 7, 8 or 9. If you head into a big corporation (eg this is a B2B tool, or something you're delivering for training) that number can rocket. Just a few months ago —in 2016— I dealt with a company using IE8 on over 60% of their machines.
So before you do anything: check what browser your users use. If you don't, you'll learn a quick and painful lesson in why "works for me" isn't good enough in a deliverable to a client.
My answer from 2008 follows.
However, there are viable non-JS methods of file uploads. You can create an iframe on the page (that you hide with CSS) and then target your form to post to that iframe. The main page doesn't need to move.
It's a "real" post so it's not wholly interactive. If you need status you need something server-side to process that. This varies massively depending on your server. ASP.NET has nicer mechanisms. PHP plain fails, but you can use Perl or Apache modifications to get around it.
If you need multiple file-uploads, it's best to do each file one at a time (to overcome maximum file upload limits). Post the first form to the iframe, monitor its progress using the above and when it has finished, post the second form to the iframe, and so on.
Or use a Java/Flash solution. They're a lot more flexible in what they can do with their posts...
137
For the record it's now possible to do pure AJAX file uploads if the browser supports the File API - developer.mozilla.org/en/using_files_from_web_applications
– meleyal
Mar 25 '11 at 10:05
33
Unless you need IE9 support. caniuse.com/fileapi
– Oli
Feb 5 '14 at 2:45
iframe solution is pretty simple and easy to get working
– Matthew Lock
Apr 17 '15 at 0:45
this is quite an old answer, but it was a bit misleading.. IE supported XHR natively as far back as IE7, and supported it through ActiveX as far back as IE5. w3schools.com/ajax/ajax_xmlhttprequest_create.asp. The practical way of doing this was certainly targeting flash (shockwave) components, or rolling out a Flash/ActiveX (Silverlight) control. If you can originate a request and handle the response via javascript, it's ajax.. though, having said that, ajax is synonymous with xhr, but it doesn't itself describe the underline mechanism/components that delivers/exchanges the payload.
– Brett Caswell
Oct 29 '15 at 14:54
4
@BrettCaswell I wasn't saying that AJAX/XHR weren't possible, just that it wasn't possible to post a file up with them on old —but everliving— versions of IE. That was and remains completely true.
– Oli
Oct 29 '15 at 15:34
add a comment |
up vote
244
down vote
up vote
244
down vote
2017 Update: It still depends on the browsers your demographic uses.
An important thing to understand with the "new" HTML5 file
API is that is wasn't supported until IE 10. If the specific market you're aiming at has a higher-than-average prepensity toward older versions of Windows, you might not have access to it.
Going into 2017, about 5% of browsers are one of IE 6, 7, 8 or 9. If you head into a big corporation (eg this is a B2B tool, or something you're delivering for training) that number can rocket. Just a few months ago —in 2016— I dealt with a company using IE8 on over 60% of their machines.
So before you do anything: check what browser your users use. If you don't, you'll learn a quick and painful lesson in why "works for me" isn't good enough in a deliverable to a client.
My answer from 2008 follows.
However, there are viable non-JS methods of file uploads. You can create an iframe on the page (that you hide with CSS) and then target your form to post to that iframe. The main page doesn't need to move.
It's a "real" post so it's not wholly interactive. If you need status you need something server-side to process that. This varies massively depending on your server. ASP.NET has nicer mechanisms. PHP plain fails, but you can use Perl or Apache modifications to get around it.
If you need multiple file-uploads, it's best to do each file one at a time (to overcome maximum file upload limits). Post the first form to the iframe, monitor its progress using the above and when it has finished, post the second form to the iframe, and so on.
Or use a Java/Flash solution. They're a lot more flexible in what they can do with their posts...
2017 Update: It still depends on the browsers your demographic uses.
An important thing to understand with the "new" HTML5 file
API is that is wasn't supported until IE 10. If the specific market you're aiming at has a higher-than-average prepensity toward older versions of Windows, you might not have access to it.
Going into 2017, about 5% of browsers are one of IE 6, 7, 8 or 9. If you head into a big corporation (eg this is a B2B tool, or something you're delivering for training) that number can rocket. Just a few months ago —in 2016— I dealt with a company using IE8 on over 60% of their machines.
So before you do anything: check what browser your users use. If you don't, you'll learn a quick and painful lesson in why "works for me" isn't good enough in a deliverable to a client.
My answer from 2008 follows.
However, there are viable non-JS methods of file uploads. You can create an iframe on the page (that you hide with CSS) and then target your form to post to that iframe. The main page doesn't need to move.
It's a "real" post so it's not wholly interactive. If you need status you need something server-side to process that. This varies massively depending on your server. ASP.NET has nicer mechanisms. PHP plain fails, but you can use Perl or Apache modifications to get around it.
If you need multiple file-uploads, it's best to do each file one at a time (to overcome maximum file upload limits). Post the first form to the iframe, monitor its progress using the above and when it has finished, post the second form to the iframe, and so on.
Or use a Java/Flash solution. They're a lot more flexible in what they can do with their posts...
edited Dec 19 '16 at 12:20
answered Oct 3 '08 at 10:41
Oli
117k52179255
117k52179255
137
For the record it's now possible to do pure AJAX file uploads if the browser supports the File API - developer.mozilla.org/en/using_files_from_web_applications
– meleyal
Mar 25 '11 at 10:05
33
Unless you need IE9 support. caniuse.com/fileapi
– Oli
Feb 5 '14 at 2:45
iframe solution is pretty simple and easy to get working
– Matthew Lock
Apr 17 '15 at 0:45
this is quite an old answer, but it was a bit misleading.. IE supported XHR natively as far back as IE7, and supported it through ActiveX as far back as IE5. w3schools.com/ajax/ajax_xmlhttprequest_create.asp. The practical way of doing this was certainly targeting flash (shockwave) components, or rolling out a Flash/ActiveX (Silverlight) control. If you can originate a request and handle the response via javascript, it's ajax.. though, having said that, ajax is synonymous with xhr, but it doesn't itself describe the underline mechanism/components that delivers/exchanges the payload.
– Brett Caswell
Oct 29 '15 at 14:54
4
@BrettCaswell I wasn't saying that AJAX/XHR weren't possible, just that it wasn't possible to post a file up with them on old —but everliving— versions of IE. That was and remains completely true.
– Oli
Oct 29 '15 at 15:34
add a comment |
137
For the record it's now possible to do pure AJAX file uploads if the browser supports the File API - developer.mozilla.org/en/using_files_from_web_applications
– meleyal
Mar 25 '11 at 10:05
33
Unless you need IE9 support. caniuse.com/fileapi
– Oli
Feb 5 '14 at 2:45
iframe solution is pretty simple and easy to get working
– Matthew Lock
Apr 17 '15 at 0:45
this is quite an old answer, but it was a bit misleading.. IE supported XHR natively as far back as IE7, and supported it through ActiveX as far back as IE5. w3schools.com/ajax/ajax_xmlhttprequest_create.asp. The practical way of doing this was certainly targeting flash (shockwave) components, or rolling out a Flash/ActiveX (Silverlight) control. If you can originate a request and handle the response via javascript, it's ajax.. though, having said that, ajax is synonymous with xhr, but it doesn't itself describe the underline mechanism/components that delivers/exchanges the payload.
– Brett Caswell
Oct 29 '15 at 14:54
4
@BrettCaswell I wasn't saying that AJAX/XHR weren't possible, just that it wasn't possible to post a file up with them on old —but everliving— versions of IE. That was and remains completely true.
– Oli
Oct 29 '15 at 15:34
137
137
For the record it's now possible to do pure AJAX file uploads if the browser supports the File API - developer.mozilla.org/en/using_files_from_web_applications
– meleyal
Mar 25 '11 at 10:05
For the record it's now possible to do pure AJAX file uploads if the browser supports the File API - developer.mozilla.org/en/using_files_from_web_applications
– meleyal
Mar 25 '11 at 10:05
33
33
Unless you need IE9 support. caniuse.com/fileapi
– Oli
Feb 5 '14 at 2:45
Unless you need IE9 support. caniuse.com/fileapi
– Oli
Feb 5 '14 at 2:45
iframe solution is pretty simple and easy to get working
– Matthew Lock
Apr 17 '15 at 0:45
iframe solution is pretty simple and easy to get working
– Matthew Lock
Apr 17 '15 at 0:45
this is quite an old answer, but it was a bit misleading.. IE supported XHR natively as far back as IE7, and supported it through ActiveX as far back as IE5. w3schools.com/ajax/ajax_xmlhttprequest_create.asp. The practical way of doing this was certainly targeting flash (shockwave) components, or rolling out a Flash/ActiveX (Silverlight) control. If you can originate a request and handle the response via javascript, it's ajax.. though, having said that, ajax is synonymous with xhr, but it doesn't itself describe the underline mechanism/components that delivers/exchanges the payload.
– Brett Caswell
Oct 29 '15 at 14:54
this is quite an old answer, but it was a bit misleading.. IE supported XHR natively as far back as IE7, and supported it through ActiveX as far back as IE5. w3schools.com/ajax/ajax_xmlhttprequest_create.asp. The practical way of doing this was certainly targeting flash (shockwave) components, or rolling out a Flash/ActiveX (Silverlight) control. If you can originate a request and handle the response via javascript, it's ajax.. though, having said that, ajax is synonymous with xhr, but it doesn't itself describe the underline mechanism/components that delivers/exchanges the payload.
– Brett Caswell
Oct 29 '15 at 14:54
4
4
@BrettCaswell I wasn't saying that AJAX/XHR weren't possible, just that it wasn't possible to post a file up with them on old —but everliving— versions of IE. That was and remains completely true.
– Oli
Oct 29 '15 at 15:34
@BrettCaswell I wasn't saying that AJAX/XHR weren't possible, just that it wasn't possible to post a file up with them on old —but everliving— versions of IE. That was and remains completely true.
– Oli
Oct 29 '15 at 15:34
add a comment |
up vote
107
down vote
I recommend using the Fine Uploader plugin for this purpose. Your JavaScript
code would be:
$(document).ready(function() {
$("#uploadbutton").jsupload({
action: "addFile.do",
onComplete: function(response){
alert( "server response: " + response);
}
});
});
It uses JSON - so for PHP old version it will be non possible use.
– Lorenzo Manucci
Jun 22 '11 at 9:35
Seems much cleaner than Ajax File Upload, where I need to include a huge piece of code just to use the damn thing.
– ripper234
Dec 6 '11 at 14:52
5
URL is now valums.com/ajax-upload.
– Patrick Fisher
Feb 12 '12 at 2:07
34
"This plugin is open sourced under GNU GPL 2 or later and GNU LGPL 2 or later." So as long as you don't distribute the copy or a modified version, you don't have to open your project.
– Trantor Liu
Jul 23 '12 at 12:02
1
This is the website (fineuploader.com) I found now, it's V4.2 .
– Andrew_1510
Feb 5 '14 at 10:25
|
show 7 more comments
up vote
107
down vote
I recommend using the Fine Uploader plugin for this purpose. Your JavaScript
code would be:
$(document).ready(function() {
$("#uploadbutton").jsupload({
action: "addFile.do",
onComplete: function(response){
alert( "server response: " + response);
}
});
});
It uses JSON - so for PHP old version it will be non possible use.
– Lorenzo Manucci
Jun 22 '11 at 9:35
Seems much cleaner than Ajax File Upload, where I need to include a huge piece of code just to use the damn thing.
– ripper234
Dec 6 '11 at 14:52
5
URL is now valums.com/ajax-upload.
– Patrick Fisher
Feb 12 '12 at 2:07
34
"This plugin is open sourced under GNU GPL 2 or later and GNU LGPL 2 or later." So as long as you don't distribute the copy or a modified version, you don't have to open your project.
– Trantor Liu
Jul 23 '12 at 12:02
1
This is the website (fineuploader.com) I found now, it's V4.2 .
– Andrew_1510
Feb 5 '14 at 10:25
|
show 7 more comments
up vote
107
down vote
up vote
107
down vote
I recommend using the Fine Uploader plugin for this purpose. Your JavaScript
code would be:
$(document).ready(function() {
$("#uploadbutton").jsupload({
action: "addFile.do",
onComplete: function(response){
alert( "server response: " + response);
}
});
});
I recommend using the Fine Uploader plugin for this purpose. Your JavaScript
code would be:
$(document).ready(function() {
$("#uploadbutton").jsupload({
action: "addFile.do",
onComplete: function(response){
alert( "server response: " + response);
}
});
});
edited Sep 19 '17 at 16:45
Shiladitya
9,39391830
9,39391830
answered Nov 21 '08 at 16:38
pixxaar
It uses JSON - so for PHP old version it will be non possible use.
– Lorenzo Manucci
Jun 22 '11 at 9:35
Seems much cleaner than Ajax File Upload, where I need to include a huge piece of code just to use the damn thing.
– ripper234
Dec 6 '11 at 14:52
5
URL is now valums.com/ajax-upload.
– Patrick Fisher
Feb 12 '12 at 2:07
34
"This plugin is open sourced under GNU GPL 2 or later and GNU LGPL 2 or later." So as long as you don't distribute the copy or a modified version, you don't have to open your project.
– Trantor Liu
Jul 23 '12 at 12:02
1
This is the website (fineuploader.com) I found now, it's V4.2 .
– Andrew_1510
Feb 5 '14 at 10:25
|
show 7 more comments
It uses JSON - so for PHP old version it will be non possible use.
– Lorenzo Manucci
Jun 22 '11 at 9:35
Seems much cleaner than Ajax File Upload, where I need to include a huge piece of code just to use the damn thing.
– ripper234
Dec 6 '11 at 14:52
5
URL is now valums.com/ajax-upload.
– Patrick Fisher
Feb 12 '12 at 2:07
34
"This plugin is open sourced under GNU GPL 2 or later and GNU LGPL 2 or later." So as long as you don't distribute the copy or a modified version, you don't have to open your project.
– Trantor Liu
Jul 23 '12 at 12:02
1
This is the website (fineuploader.com) I found now, it's V4.2 .
– Andrew_1510
Feb 5 '14 at 10:25
It uses JSON - so for PHP old version it will be non possible use.
– Lorenzo Manucci
Jun 22 '11 at 9:35
It uses JSON - so for PHP old version it will be non possible use.
– Lorenzo Manucci
Jun 22 '11 at 9:35
Seems much cleaner than Ajax File Upload, where I need to include a huge piece of code just to use the damn thing.
– ripper234
Dec 6 '11 at 14:52
Seems much cleaner than Ajax File Upload, where I need to include a huge piece of code just to use the damn thing.
– ripper234
Dec 6 '11 at 14:52
5
5
URL is now valums.com/ajax-upload.
– Patrick Fisher
Feb 12 '12 at 2:07
URL is now valums.com/ajax-upload.
– Patrick Fisher
Feb 12 '12 at 2:07
34
34
"This plugin is open sourced under GNU GPL 2 or later and GNU LGPL 2 or later." So as long as you don't distribute the copy or a modified version, you don't have to open your project.
– Trantor Liu
Jul 23 '12 at 12:02
"This plugin is open sourced under GNU GPL 2 or later and GNU LGPL 2 or later." So as long as you don't distribute the copy or a modified version, you don't have to open your project.
– Trantor Liu
Jul 23 '12 at 12:02
1
1
This is the website (fineuploader.com) I found now, it's V4.2 .
– Andrew_1510
Feb 5 '14 at 10:25
This is the website (fineuploader.com) I found now, it's V4.2 .
– Andrew_1510
Feb 5 '14 at 10:25
|
show 7 more comments
up vote
92
down vote
Note: This answer is outdated, it is now possible to upload files using XHR.
You cannot upload files using XMLHttpRequest (Ajax). You can simulate the effect using an iframe or Flash. The excellent jQuery Form Plugin that posts your files through an iframe to get the effect.
1
Yes, you can POST to an iframe and capture the file there. I have very limited experience with this though, so I can't really comment on it.
– Mattias
Oct 3 '08 at 17:21
15
Small remark: in latest versions of chrome and firefox it is possible, stackoverflow.com/questions/4856917/…
– Alleo
Nov 3 '11 at 18:57
Not supported in IE9 and less
– Radmation
Sep 7 at 20:43
add a comment |
up vote
92
down vote
Note: This answer is outdated, it is now possible to upload files using XHR.
You cannot upload files using XMLHttpRequest (Ajax). You can simulate the effect using an iframe or Flash. The excellent jQuery Form Plugin that posts your files through an iframe to get the effect.
1
Yes, you can POST to an iframe and capture the file there. I have very limited experience with this though, so I can't really comment on it.
– Mattias
Oct 3 '08 at 17:21
15
Small remark: in latest versions of chrome and firefox it is possible, stackoverflow.com/questions/4856917/…
– Alleo
Nov 3 '11 at 18:57
Not supported in IE9 and less
– Radmation
Sep 7 at 20:43
add a comment |
up vote
92
down vote
up vote
92
down vote
Note: This answer is outdated, it is now possible to upload files using XHR.
You cannot upload files using XMLHttpRequest (Ajax). You can simulate the effect using an iframe or Flash. The excellent jQuery Form Plugin that posts your files through an iframe to get the effect.
Note: This answer is outdated, it is now possible to upload files using XHR.
You cannot upload files using XMLHttpRequest (Ajax). You can simulate the effect using an iframe or Flash. The excellent jQuery Form Plugin that posts your files through an iframe to get the effect.
edited Jun 15 at 8:10
tiermix
426
426
answered Oct 3 '08 at 10:36
Mattias
2,43031817
2,43031817
1
Yes, you can POST to an iframe and capture the file there. I have very limited experience with this though, so I can't really comment on it.
– Mattias
Oct 3 '08 at 17:21
15
Small remark: in latest versions of chrome and firefox it is possible, stackoverflow.com/questions/4856917/…
– Alleo
Nov 3 '11 at 18:57
Not supported in IE9 and less
– Radmation
Sep 7 at 20:43
add a comment |
1
Yes, you can POST to an iframe and capture the file there. I have very limited experience with this though, so I can't really comment on it.
– Mattias
Oct 3 '08 at 17:21
15
Small remark: in latest versions of chrome and firefox it is possible, stackoverflow.com/questions/4856917/…
– Alleo
Nov 3 '11 at 18:57
Not supported in IE9 and less
– Radmation
Sep 7 at 20:43
1
1
Yes, you can POST to an iframe and capture the file there. I have very limited experience with this though, so I can't really comment on it.
– Mattias
Oct 3 '08 at 17:21
Yes, you can POST to an iframe and capture the file there. I have very limited experience with this though, so I can't really comment on it.
– Mattias
Oct 3 '08 at 17:21
15
15
Small remark: in latest versions of chrome and firefox it is possible, stackoverflow.com/questions/4856917/…
– Alleo
Nov 3 '11 at 18:57
Small remark: in latest versions of chrome and firefox it is possible, stackoverflow.com/questions/4856917/…
– Alleo
Nov 3 '11 at 18:57
Not supported in IE9 and less
– Radmation
Sep 7 at 20:43
Not supported in IE9 and less
– Radmation
Sep 7 at 20:43
add a comment |
up vote
82
down vote
This AJAX file upload jQuery plugin uploads the file somehwere, and passes the
response to a callback, nothing else.
- It does not depend on specific HTML, just give it a
<input type="file">
- It does not require your server to respond in any particular way
- It does not matter how many files you use, or where they are on the page
-- Use as little as --
$('#one-specific-file').ajaxfileupload({
'action': '/upload.php'
});
-- or as much as --
$('input[type="file"]').ajaxfileupload({
'action': '/upload.php',
'params': {
'extra': 'info'
},
'onComplete': function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
},
'onStart': function() {
if(weWantedTo) return false; // cancels upload
},
'onCancel': function() {
console.log('no file selected');
}
});
4
Not working with 1.9.1 :|
– user840250
Mar 24 '13 at 11:31
1
@user840250 jQuery 1.9.1?
– Jordan Feldstein
Mar 25 '13 at 17:33
add a comment |
up vote
82
down vote
This AJAX file upload jQuery plugin uploads the file somehwere, and passes the
response to a callback, nothing else.
- It does not depend on specific HTML, just give it a
<input type="file">
- It does not require your server to respond in any particular way
- It does not matter how many files you use, or where they are on the page
-- Use as little as --
$('#one-specific-file').ajaxfileupload({
'action': '/upload.php'
});
-- or as much as --
$('input[type="file"]').ajaxfileupload({
'action': '/upload.php',
'params': {
'extra': 'info'
},
'onComplete': function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
},
'onStart': function() {
if(weWantedTo) return false; // cancels upload
},
'onCancel': function() {
console.log('no file selected');
}
});
4
Not working with 1.9.1 :|
– user840250
Mar 24 '13 at 11:31
1
@user840250 jQuery 1.9.1?
– Jordan Feldstein
Mar 25 '13 at 17:33
add a comment |
up vote
82
down vote
up vote
82
down vote
This AJAX file upload jQuery plugin uploads the file somehwere, and passes the
response to a callback, nothing else.
- It does not depend on specific HTML, just give it a
<input type="file">
- It does not require your server to respond in any particular way
- It does not matter how many files you use, or where they are on the page
-- Use as little as --
$('#one-specific-file').ajaxfileupload({
'action': '/upload.php'
});
-- or as much as --
$('input[type="file"]').ajaxfileupload({
'action': '/upload.php',
'params': {
'extra': 'info'
},
'onComplete': function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
},
'onStart': function() {
if(weWantedTo) return false; // cancels upload
},
'onCancel': function() {
console.log('no file selected');
}
});
This AJAX file upload jQuery plugin uploads the file somehwere, and passes the
response to a callback, nothing else.
- It does not depend on specific HTML, just give it a
<input type="file">
- It does not require your server to respond in any particular way
- It does not matter how many files you use, or where they are on the page
-- Use as little as --
$('#one-specific-file').ajaxfileupload({
'action': '/upload.php'
});
-- or as much as --
$('input[type="file"]').ajaxfileupload({
'action': '/upload.php',
'params': {
'extra': 'info'
},
'onComplete': function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
},
'onStart': function() {
if(weWantedTo) return false; // cancels upload
},
'onCancel': function() {
console.log('no file selected');
}
});
answered Jul 29 '11 at 0:34
Jordan Feldstein
6,04384074
6,04384074
4
Not working with 1.9.1 :|
– user840250
Mar 24 '13 at 11:31
1
@user840250 jQuery 1.9.1?
– Jordan Feldstein
Mar 25 '13 at 17:33
add a comment |
4
Not working with 1.9.1 :|
– user840250
Mar 24 '13 at 11:31
1
@user840250 jQuery 1.9.1?
– Jordan Feldstein
Mar 25 '13 at 17:33
4
4
Not working with 1.9.1 :|
– user840250
Mar 24 '13 at 11:31
Not working with 1.9.1 :|
– user840250
Mar 24 '13 at 11:31
1
1
@user840250 jQuery 1.9.1?
– Jordan Feldstein
Mar 25 '13 at 17:33
@user840250 jQuery 1.9.1?
– Jordan Feldstein
Mar 25 '13 at 17:33
add a comment |
up vote
81
down vote
Wrapping up for future readers.
Asynchronous File Upload
With HTML5
You can upload files with jQuery using the $.ajax()
method if FormData and the File API are supported (both HTML5 features).
You can also send files without FormData but either way the File API must be present to process files in such a way that they can be sent with XMLHttpRequest (Ajax).
$.ajax({
url: 'file/destination.html',
type: 'POST',
data: new FormData($('#formWithFiles')[0]), // The form with the file inputs.
processData: false,
contentType: false // Using FormData, no need to process data.
}).done(function(){
console.log("Success: Files sent!");
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
For a quick, pure JavaScript (no jQuery) example see "Sending files using a FormData object".
Fallback
When HTML5 isn't supported (no File API) the only other pure JavaScript solution (no Flash or any other browser plugin) is the hidden iframe technique, which allows to emulate an asynchronous request without using the XMLHttpRequest object.
It consists of setting an iframe as the target of the form with the file inputs. When the user submits a request is made and the files are uploaded but the response is displayed inside the iframe instead of re-rendering the main page. Hiding the iframe makes the whole process transparent to the user and emulates an asynchronous request.
If done properly it should work virtually on any browser, but it has some caveats as how to obtain the response from the iframe.
In this case you may prefer to use a wrapper plugin like Bifröst which uses the iframe technique but also provides a jQuery Ajax transport allowing to send files with just the $.ajax()
method like this:
$.ajax({
url: 'file/destination.html',
type: 'POST',
// Set the transport to use (iframe means to use Bifröst)
// and the expected data type (json in this case).
dataType: 'iframe json',
fileInputs: $('input[type="file"]'), // The file inputs containing the files to send.
data: { msg: 'Some extra data you might need.'}
}).done(function(){
console.log("Success: Files sent!");
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
Plugins
Bifröst is just a small wrapper that adds fallback support to jQuery's ajax method, but many of the aforementioned plugins like jQuery Form Plugin or jQuery File Upload include the whole stack from HTML5 to different fallbacks and some useful features to ease out the process. Depending on your needs and requirements you might want to consider a bare implementation or either of this plugins.
3
One thing to note, based on the documentation: you should also sendcontentType: false
. When I didn't send this with chrome the form content type was invalidated by jQuery.
– ash
Aug 18 '15 at 22:44
Nice answer. A few suggestions for improvement: Remove the parts of the code unrelated to the answer, for example the.done()
and.fail()
callbacks. Also, an example without the use ofFormData
and a list of pro/cons would be awesome.
– Zero3
Dec 19 '15 at 18:10
I got this error:TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
– candlejack
Dec 25 '16 at 23:15
add a comment |
up vote
81
down vote
Wrapping up for future readers.
Asynchronous File Upload
With HTML5
You can upload files with jQuery using the $.ajax()
method if FormData and the File API are supported (both HTML5 features).
You can also send files without FormData but either way the File API must be present to process files in such a way that they can be sent with XMLHttpRequest (Ajax).
$.ajax({
url: 'file/destination.html',
type: 'POST',
data: new FormData($('#formWithFiles')[0]), // The form with the file inputs.
processData: false,
contentType: false // Using FormData, no need to process data.
}).done(function(){
console.log("Success: Files sent!");
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
For a quick, pure JavaScript (no jQuery) example see "Sending files using a FormData object".
Fallback
When HTML5 isn't supported (no File API) the only other pure JavaScript solution (no Flash or any other browser plugin) is the hidden iframe technique, which allows to emulate an asynchronous request without using the XMLHttpRequest object.
It consists of setting an iframe as the target of the form with the file inputs. When the user submits a request is made and the files are uploaded but the response is displayed inside the iframe instead of re-rendering the main page. Hiding the iframe makes the whole process transparent to the user and emulates an asynchronous request.
If done properly it should work virtually on any browser, but it has some caveats as how to obtain the response from the iframe.
In this case you may prefer to use a wrapper plugin like Bifröst which uses the iframe technique but also provides a jQuery Ajax transport allowing to send files with just the $.ajax()
method like this:
$.ajax({
url: 'file/destination.html',
type: 'POST',
// Set the transport to use (iframe means to use Bifröst)
// and the expected data type (json in this case).
dataType: 'iframe json',
fileInputs: $('input[type="file"]'), // The file inputs containing the files to send.
data: { msg: 'Some extra data you might need.'}
}).done(function(){
console.log("Success: Files sent!");
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
Plugins
Bifröst is just a small wrapper that adds fallback support to jQuery's ajax method, but many of the aforementioned plugins like jQuery Form Plugin or jQuery File Upload include the whole stack from HTML5 to different fallbacks and some useful features to ease out the process. Depending on your needs and requirements you might want to consider a bare implementation or either of this plugins.
3
One thing to note, based on the documentation: you should also sendcontentType: false
. When I didn't send this with chrome the form content type was invalidated by jQuery.
– ash
Aug 18 '15 at 22:44
Nice answer. A few suggestions for improvement: Remove the parts of the code unrelated to the answer, for example the.done()
and.fail()
callbacks. Also, an example without the use ofFormData
and a list of pro/cons would be awesome.
– Zero3
Dec 19 '15 at 18:10
I got this error:TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
– candlejack
Dec 25 '16 at 23:15
add a comment |
up vote
81
down vote
up vote
81
down vote
Wrapping up for future readers.
Asynchronous File Upload
With HTML5
You can upload files with jQuery using the $.ajax()
method if FormData and the File API are supported (both HTML5 features).
You can also send files without FormData but either way the File API must be present to process files in such a way that they can be sent with XMLHttpRequest (Ajax).
$.ajax({
url: 'file/destination.html',
type: 'POST',
data: new FormData($('#formWithFiles')[0]), // The form with the file inputs.
processData: false,
contentType: false // Using FormData, no need to process data.
}).done(function(){
console.log("Success: Files sent!");
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
For a quick, pure JavaScript (no jQuery) example see "Sending files using a FormData object".
Fallback
When HTML5 isn't supported (no File API) the only other pure JavaScript solution (no Flash or any other browser plugin) is the hidden iframe technique, which allows to emulate an asynchronous request without using the XMLHttpRequest object.
It consists of setting an iframe as the target of the form with the file inputs. When the user submits a request is made and the files are uploaded but the response is displayed inside the iframe instead of re-rendering the main page. Hiding the iframe makes the whole process transparent to the user and emulates an asynchronous request.
If done properly it should work virtually on any browser, but it has some caveats as how to obtain the response from the iframe.
In this case you may prefer to use a wrapper plugin like Bifröst which uses the iframe technique but also provides a jQuery Ajax transport allowing to send files with just the $.ajax()
method like this:
$.ajax({
url: 'file/destination.html',
type: 'POST',
// Set the transport to use (iframe means to use Bifröst)
// and the expected data type (json in this case).
dataType: 'iframe json',
fileInputs: $('input[type="file"]'), // The file inputs containing the files to send.
data: { msg: 'Some extra data you might need.'}
}).done(function(){
console.log("Success: Files sent!");
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
Plugins
Bifröst is just a small wrapper that adds fallback support to jQuery's ajax method, but many of the aforementioned plugins like jQuery Form Plugin or jQuery File Upload include the whole stack from HTML5 to different fallbacks and some useful features to ease out the process. Depending on your needs and requirements you might want to consider a bare implementation or either of this plugins.
Wrapping up for future readers.
Asynchronous File Upload
With HTML5
You can upload files with jQuery using the $.ajax()
method if FormData and the File API are supported (both HTML5 features).
You can also send files without FormData but either way the File API must be present to process files in such a way that they can be sent with XMLHttpRequest (Ajax).
$.ajax({
url: 'file/destination.html',
type: 'POST',
data: new FormData($('#formWithFiles')[0]), // The form with the file inputs.
processData: false,
contentType: false // Using FormData, no need to process data.
}).done(function(){
console.log("Success: Files sent!");
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
For a quick, pure JavaScript (no jQuery) example see "Sending files using a FormData object".
Fallback
When HTML5 isn't supported (no File API) the only other pure JavaScript solution (no Flash or any other browser plugin) is the hidden iframe technique, which allows to emulate an asynchronous request without using the XMLHttpRequest object.
It consists of setting an iframe as the target of the form with the file inputs. When the user submits a request is made and the files are uploaded but the response is displayed inside the iframe instead of re-rendering the main page. Hiding the iframe makes the whole process transparent to the user and emulates an asynchronous request.
If done properly it should work virtually on any browser, but it has some caveats as how to obtain the response from the iframe.
In this case you may prefer to use a wrapper plugin like Bifröst which uses the iframe technique but also provides a jQuery Ajax transport allowing to send files with just the $.ajax()
method like this:
$.ajax({
url: 'file/destination.html',
type: 'POST',
// Set the transport to use (iframe means to use Bifröst)
// and the expected data type (json in this case).
dataType: 'iframe json',
fileInputs: $('input[type="file"]'), // The file inputs containing the files to send.
data: { msg: 'Some extra data you might need.'}
}).done(function(){
console.log("Success: Files sent!");
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
Plugins
Bifröst is just a small wrapper that adds fallback support to jQuery's ajax method, but many of the aforementioned plugins like jQuery Form Plugin or jQuery File Upload include the whole stack from HTML5 to different fallbacks and some useful features to ease out the process. Depending on your needs and requirements you might want to consider a bare implementation or either of this plugins.
edited Jun 18 at 21:15
Danimal Reks
417
417
answered Aug 25 '14 at 14:17
404
1,11286
1,11286
3
One thing to note, based on the documentation: you should also sendcontentType: false
. When I didn't send this with chrome the form content type was invalidated by jQuery.
– ash
Aug 18 '15 at 22:44
Nice answer. A few suggestions for improvement: Remove the parts of the code unrelated to the answer, for example the.done()
and.fail()
callbacks. Also, an example without the use ofFormData
and a list of pro/cons would be awesome.
– Zero3
Dec 19 '15 at 18:10
I got this error:TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
– candlejack
Dec 25 '16 at 23:15
add a comment |
3
One thing to note, based on the documentation: you should also sendcontentType: false
. When I didn't send this with chrome the form content type was invalidated by jQuery.
– ash
Aug 18 '15 at 22:44
Nice answer. A few suggestions for improvement: Remove the parts of the code unrelated to the answer, for example the.done()
and.fail()
callbacks. Also, an example without the use ofFormData
and a list of pro/cons would be awesome.
– Zero3
Dec 19 '15 at 18:10
I got this error:TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
– candlejack
Dec 25 '16 at 23:15
3
3
One thing to note, based on the documentation: you should also send
contentType: false
. When I didn't send this with chrome the form content type was invalidated by jQuery.– ash
Aug 18 '15 at 22:44
One thing to note, based on the documentation: you should also send
contentType: false
. When I didn't send this with chrome the form content type was invalidated by jQuery.– ash
Aug 18 '15 at 22:44
Nice answer. A few suggestions for improvement: Remove the parts of the code unrelated to the answer, for example the
.done()
and .fail()
callbacks. Also, an example without the use of FormData
and a list of pro/cons would be awesome.– Zero3
Dec 19 '15 at 18:10
Nice answer. A few suggestions for improvement: Remove the parts of the code unrelated to the answer, for example the
.done()
and .fail()
callbacks. Also, an example without the use of FormData
and a list of pro/cons would be awesome.– Zero3
Dec 19 '15 at 18:10
I got this error:
TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
– candlejack
Dec 25 '16 at 23:15
I got this error:
TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
– candlejack
Dec 25 '16 at 23:15
add a comment |
up vote
58
down vote
I have been using the below script to upload images which happens to work fine.
HTML
<input id="file" type="file" name="file"/>
<div id="response"></div>
JavaScript
jQuery('document').ready(function(){
var input = document.getElementById("file");
var formdata = false;
if (window.FormData) {
formdata = new FormData();
}
input.addEventListener("change", function (evt) {
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
//showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("image", file);
formdata.append("extra",'extra-data');
}
if (formdata) {
jQuery('div#response').html('<br /><img src="ajax-loader.gif"/>');
jQuery.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
jQuery('div#response').html("Successfully uploaded");
}
});
}
}
else
{
alert('Not a vaild image!');
}
}
}, false);
});
Explanation
I use response div
to show the uploading animation and response after upload is done.
Best part is you can send extra data such as ids & etc with the file when you use this script. I have mention it extra-data
as in the script.
At the PHP level this will work as normal file upload. extra-data can be retrieved as $_POST
data.
Here you are not using a plugin and stuff. You can change the code as you want. You are not blindly coding here. This is the core functionality of any jQuery file upload. Actually Javascript.
5
-1 for using jQuery and not using it's selector engine and event handlers.addEventListener
is not cross-browser.
– Mark
Sep 22 '13 at 20:49
3
Because it would be pointless to add a separate answer which would be mostly based on this one, with just a few changes. Instead, this answer should be corrected.
– Mark
Nov 23 '13 at 16:14
2
@RainFromHeaven, please, can you edit the answer? I don't know how to do it in the cross-browser way.
– Thiago Negri
Jan 27 '14 at 13:57
2
Still does not work in IE 9 and down. Allot of users still use those versions of IE.
– Pierre
Jun 28 '14 at 10:48
1
Can someone please explain how can this be made to work in asp.net? Do I use webmethod? If yes what would it look like?
– Arbaaz
May 23 '15 at 5:23
add a comment |
up vote
58
down vote
I have been using the below script to upload images which happens to work fine.
HTML
<input id="file" type="file" name="file"/>
<div id="response"></div>
JavaScript
jQuery('document').ready(function(){
var input = document.getElementById("file");
var formdata = false;
if (window.FormData) {
formdata = new FormData();
}
input.addEventListener("change", function (evt) {
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
//showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("image", file);
formdata.append("extra",'extra-data');
}
if (formdata) {
jQuery('div#response').html('<br /><img src="ajax-loader.gif"/>');
jQuery.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
jQuery('div#response').html("Successfully uploaded");
}
});
}
}
else
{
alert('Not a vaild image!');
}
}
}, false);
});
Explanation
I use response div
to show the uploading animation and response after upload is done.
Best part is you can send extra data such as ids & etc with the file when you use this script. I have mention it extra-data
as in the script.
At the PHP level this will work as normal file upload. extra-data can be retrieved as $_POST
data.
Here you are not using a plugin and stuff. You can change the code as you want. You are not blindly coding here. This is the core functionality of any jQuery file upload. Actually Javascript.
5
-1 for using jQuery and not using it's selector engine and event handlers.addEventListener
is not cross-browser.
– Mark
Sep 22 '13 at 20:49
3
Because it would be pointless to add a separate answer which would be mostly based on this one, with just a few changes. Instead, this answer should be corrected.
– Mark
Nov 23 '13 at 16:14
2
@RainFromHeaven, please, can you edit the answer? I don't know how to do it in the cross-browser way.
– Thiago Negri
Jan 27 '14 at 13:57
2
Still does not work in IE 9 and down. Allot of users still use those versions of IE.
– Pierre
Jun 28 '14 at 10:48
1
Can someone please explain how can this be made to work in asp.net? Do I use webmethod? If yes what would it look like?
– Arbaaz
May 23 '15 at 5:23
add a comment |
up vote
58
down vote
up vote
58
down vote
I have been using the below script to upload images which happens to work fine.
HTML
<input id="file" type="file" name="file"/>
<div id="response"></div>
JavaScript
jQuery('document').ready(function(){
var input = document.getElementById("file");
var formdata = false;
if (window.FormData) {
formdata = new FormData();
}
input.addEventListener("change", function (evt) {
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
//showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("image", file);
formdata.append("extra",'extra-data');
}
if (formdata) {
jQuery('div#response').html('<br /><img src="ajax-loader.gif"/>');
jQuery.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
jQuery('div#response').html("Successfully uploaded");
}
});
}
}
else
{
alert('Not a vaild image!');
}
}
}, false);
});
Explanation
I use response div
to show the uploading animation and response after upload is done.
Best part is you can send extra data such as ids & etc with the file when you use this script. I have mention it extra-data
as in the script.
At the PHP level this will work as normal file upload. extra-data can be retrieved as $_POST
data.
Here you are not using a plugin and stuff. You can change the code as you want. You are not blindly coding here. This is the core functionality of any jQuery file upload. Actually Javascript.
I have been using the below script to upload images which happens to work fine.
HTML
<input id="file" type="file" name="file"/>
<div id="response"></div>
JavaScript
jQuery('document').ready(function(){
var input = document.getElementById("file");
var formdata = false;
if (window.FormData) {
formdata = new FormData();
}
input.addEventListener("change", function (evt) {
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
//showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("image", file);
formdata.append("extra",'extra-data');
}
if (formdata) {
jQuery('div#response').html('<br /><img src="ajax-loader.gif"/>');
jQuery.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
jQuery('div#response').html("Successfully uploaded");
}
});
}
}
else
{
alert('Not a vaild image!');
}
}
}, false);
});
Explanation
I use response div
to show the uploading animation and response after upload is done.
Best part is you can send extra data such as ids & etc with the file when you use this script. I have mention it extra-data
as in the script.
At the PHP level this will work as normal file upload. extra-data can be retrieved as $_POST
data.
Here you are not using a plugin and stuff. You can change the code as you want. You are not blindly coding here. This is the core functionality of any jQuery file upload. Actually Javascript.
edited Feb 9 '14 at 10:39
Peter Mortensen
13.4k1983111
13.4k1983111
answered Jan 25 '13 at 11:03
Techie
29.1k33124204
29.1k33124204
5
-1 for using jQuery and not using it's selector engine and event handlers.addEventListener
is not cross-browser.
– Mark
Sep 22 '13 at 20:49
3
Because it would be pointless to add a separate answer which would be mostly based on this one, with just a few changes. Instead, this answer should be corrected.
– Mark
Nov 23 '13 at 16:14
2
@RainFromHeaven, please, can you edit the answer? I don't know how to do it in the cross-browser way.
– Thiago Negri
Jan 27 '14 at 13:57
2
Still does not work in IE 9 and down. Allot of users still use those versions of IE.
– Pierre
Jun 28 '14 at 10:48
1
Can someone please explain how can this be made to work in asp.net? Do I use webmethod? If yes what would it look like?
– Arbaaz
May 23 '15 at 5:23
add a comment |
5
-1 for using jQuery and not using it's selector engine and event handlers.addEventListener
is not cross-browser.
– Mark
Sep 22 '13 at 20:49
3
Because it would be pointless to add a separate answer which would be mostly based on this one, with just a few changes. Instead, this answer should be corrected.
– Mark
Nov 23 '13 at 16:14
2
@RainFromHeaven, please, can you edit the answer? I don't know how to do it in the cross-browser way.
– Thiago Negri
Jan 27 '14 at 13:57
2
Still does not work in IE 9 and down. Allot of users still use those versions of IE.
– Pierre
Jun 28 '14 at 10:48
1
Can someone please explain how can this be made to work in asp.net? Do I use webmethod? If yes what would it look like?
– Arbaaz
May 23 '15 at 5:23
5
5
-1 for using jQuery and not using it's selector engine and event handlers.
addEventListener
is not cross-browser.– Mark
Sep 22 '13 at 20:49
-1 for using jQuery and not using it's selector engine and event handlers.
addEventListener
is not cross-browser.– Mark
Sep 22 '13 at 20:49
3
3
Because it would be pointless to add a separate answer which would be mostly based on this one, with just a few changes. Instead, this answer should be corrected.
– Mark
Nov 23 '13 at 16:14
Because it would be pointless to add a separate answer which would be mostly based on this one, with just a few changes. Instead, this answer should be corrected.
– Mark
Nov 23 '13 at 16:14
2
2
@RainFromHeaven, please, can you edit the answer? I don't know how to do it in the cross-browser way.
– Thiago Negri
Jan 27 '14 at 13:57
@RainFromHeaven, please, can you edit the answer? I don't know how to do it in the cross-browser way.
– Thiago Negri
Jan 27 '14 at 13:57
2
2
Still does not work in IE 9 and down. Allot of users still use those versions of IE.
– Pierre
Jun 28 '14 at 10:48
Still does not work in IE 9 and down. Allot of users still use those versions of IE.
– Pierre
Jun 28 '14 at 10:48
1
1
Can someone please explain how can this be made to work in asp.net? Do I use webmethod? If yes what would it look like?
– Arbaaz
May 23 '15 at 5:23
Can someone please explain how can this be made to work in asp.net? Do I use webmethod? If yes what would it look like?
– Arbaaz
May 23 '15 at 5:23
add a comment |
up vote
56
down vote
I've come across a few really powerful jQuery-based file upload libraries. Check these out:
Plupload
- docs: http://www.plupload.com/docs
- docs: http://www.plupload.com/docs
jQuery File Upload
- docs: https://github.com/blueimp/jQuery-File-Upload
- docs: https://github.com/blueimp/jQuery-File-Upload
FineUploader
- docs: http://docs.fineuploader.com/
- docs: http://docs.fineuploader.com/
add a comment |
up vote
56
down vote
I've come across a few really powerful jQuery-based file upload libraries. Check these out:
Plupload
- docs: http://www.plupload.com/docs
- docs: http://www.plupload.com/docs
jQuery File Upload
- docs: https://github.com/blueimp/jQuery-File-Upload
- docs: https://github.com/blueimp/jQuery-File-Upload
FineUploader
- docs: http://docs.fineuploader.com/
- docs: http://docs.fineuploader.com/
add a comment |
up vote
56
down vote
up vote
56
down vote
I've come across a few really powerful jQuery-based file upload libraries. Check these out:
Plupload
- docs: http://www.plupload.com/docs
- docs: http://www.plupload.com/docs
jQuery File Upload
- docs: https://github.com/blueimp/jQuery-File-Upload
- docs: https://github.com/blueimp/jQuery-File-Upload
FineUploader
- docs: http://docs.fineuploader.com/
- docs: http://docs.fineuploader.com/
I've come across a few really powerful jQuery-based file upload libraries. Check these out:
Plupload
- docs: http://www.plupload.com/docs
- docs: http://www.plupload.com/docs
jQuery File Upload
- docs: https://github.com/blueimp/jQuery-File-Upload
- docs: https://github.com/blueimp/jQuery-File-Upload
FineUploader
- docs: http://docs.fineuploader.com/
- docs: http://docs.fineuploader.com/
edited Mar 1 '15 at 20:25
answered Apr 8 '11 at 16:43
Hristo
23.8k54146213
23.8k54146213
add a comment |
add a comment |
up vote
42
down vote
You can upload simply with jQuery .ajax()
.
HTML:
<form id="upload-form">
<div>
<label for="file">File:</label>
<input type="file" id="file" name="file" />
<progress class="progress" value="0" max="100"></progress>
</div>
<hr />
<input type="submit" value="Submit" />
</form>
CSS
.progress { display: none; }
Javascript:
$(document).ready(function(ev) {
$("#upload-form").on('submit', (function(ev) {
ev.preventDefault();
$.ajax({
xhr: function() {
var progress = $('.progress'),
xhr = $.ajaxSettings.xhr();
progress.show();
xhr.upload.onprogress = function(ev) {
if (ev.lengthComputable) {
var percentComplete = parseInt((ev.loaded / ev.total) * 100);
progress.val(percentComplete);
if (percentComplete === 100) {
progress.hide().val(0);
}
}
};
return xhr;
},
url: 'upload.php',
type: 'POST',
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data, status, xhr) {
// ...
},
error: function(xhr, status, error) {
// ...
}
});
}));
});
What jQuery library do I need t o run this code?
– Rayden Black
Dec 16 '15 at 2:32
1
@RaydenBlack only jQuery.
– Zayn Ali
Dec 18 '15 at 0:34
how to get upload progress?
– Ali Sherafat
Jul 22 '17 at 18:24
@AliSherafat i've updated my answer. try it
– Zayn Ali
Jul 23 '17 at 0:53
add a comment |
up vote
42
down vote
You can upload simply with jQuery .ajax()
.
HTML:
<form id="upload-form">
<div>
<label for="file">File:</label>
<input type="file" id="file" name="file" />
<progress class="progress" value="0" max="100"></progress>
</div>
<hr />
<input type="submit" value="Submit" />
</form>
CSS
.progress { display: none; }
Javascript:
$(document).ready(function(ev) {
$("#upload-form").on('submit', (function(ev) {
ev.preventDefault();
$.ajax({
xhr: function() {
var progress = $('.progress'),
xhr = $.ajaxSettings.xhr();
progress.show();
xhr.upload.onprogress = function(ev) {
if (ev.lengthComputable) {
var percentComplete = parseInt((ev.loaded / ev.total) * 100);
progress.val(percentComplete);
if (percentComplete === 100) {
progress.hide().val(0);
}
}
};
return xhr;
},
url: 'upload.php',
type: 'POST',
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data, status, xhr) {
// ...
},
error: function(xhr, status, error) {
// ...
}
});
}));
});
What jQuery library do I need t o run this code?
– Rayden Black
Dec 16 '15 at 2:32
1
@RaydenBlack only jQuery.
– Zayn Ali
Dec 18 '15 at 0:34
how to get upload progress?
– Ali Sherafat
Jul 22 '17 at 18:24
@AliSherafat i've updated my answer. try it
– Zayn Ali
Jul 23 '17 at 0:53
add a comment |
up vote
42
down vote
up vote
42
down vote
You can upload simply with jQuery .ajax()
.
HTML:
<form id="upload-form">
<div>
<label for="file">File:</label>
<input type="file" id="file" name="file" />
<progress class="progress" value="0" max="100"></progress>
</div>
<hr />
<input type="submit" value="Submit" />
</form>
CSS
.progress { display: none; }
Javascript:
$(document).ready(function(ev) {
$("#upload-form").on('submit', (function(ev) {
ev.preventDefault();
$.ajax({
xhr: function() {
var progress = $('.progress'),
xhr = $.ajaxSettings.xhr();
progress.show();
xhr.upload.onprogress = function(ev) {
if (ev.lengthComputable) {
var percentComplete = parseInt((ev.loaded / ev.total) * 100);
progress.val(percentComplete);
if (percentComplete === 100) {
progress.hide().val(0);
}
}
};
return xhr;
},
url: 'upload.php',
type: 'POST',
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data, status, xhr) {
// ...
},
error: function(xhr, status, error) {
// ...
}
});
}));
});
You can upload simply with jQuery .ajax()
.
HTML:
<form id="upload-form">
<div>
<label for="file">File:</label>
<input type="file" id="file" name="file" />
<progress class="progress" value="0" max="100"></progress>
</div>
<hr />
<input type="submit" value="Submit" />
</form>
CSS
.progress { display: none; }
Javascript:
$(document).ready(function(ev) {
$("#upload-form").on('submit', (function(ev) {
ev.preventDefault();
$.ajax({
xhr: function() {
var progress = $('.progress'),
xhr = $.ajaxSettings.xhr();
progress.show();
xhr.upload.onprogress = function(ev) {
if (ev.lengthComputable) {
var percentComplete = parseInt((ev.loaded / ev.total) * 100);
progress.val(percentComplete);
if (percentComplete === 100) {
progress.hide().val(0);
}
}
};
return xhr;
},
url: 'upload.php',
type: 'POST',
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data, status, xhr) {
// ...
},
error: function(xhr, status, error) {
// ...
}
});
}));
});
edited Oct 9 '17 at 19:53
answered Aug 8 '14 at 2:59
Zayn Ali
3,05511834
3,05511834
What jQuery library do I need t o run this code?
– Rayden Black
Dec 16 '15 at 2:32
1
@RaydenBlack only jQuery.
– Zayn Ali
Dec 18 '15 at 0:34
how to get upload progress?
– Ali Sherafat
Jul 22 '17 at 18:24
@AliSherafat i've updated my answer. try it
– Zayn Ali
Jul 23 '17 at 0:53
add a comment |
What jQuery library do I need t o run this code?
– Rayden Black
Dec 16 '15 at 2:32
1
@RaydenBlack only jQuery.
– Zayn Ali
Dec 18 '15 at 0:34
how to get upload progress?
– Ali Sherafat
Jul 22 '17 at 18:24
@AliSherafat i've updated my answer. try it
– Zayn Ali
Jul 23 '17 at 0:53
What jQuery library do I need t o run this code?
– Rayden Black
Dec 16 '15 at 2:32
What jQuery library do I need t o run this code?
– Rayden Black
Dec 16 '15 at 2:32
1
1
@RaydenBlack only jQuery.
– Zayn Ali
Dec 18 '15 at 0:34
@RaydenBlack only jQuery.
– Zayn Ali
Dec 18 '15 at 0:34
how to get upload progress?
– Ali Sherafat
Jul 22 '17 at 18:24
how to get upload progress?
– Ali Sherafat
Jul 22 '17 at 18:24
@AliSherafat i've updated my answer. try it
– Zayn Ali
Jul 23 '17 at 0:53
@AliSherafat i've updated my answer. try it
– Zayn Ali
Jul 23 '17 at 0:53
add a comment |
up vote
41
down vote
You can do it in vanilla JavaScript pretty easily. Here's a snippet from my current project:
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
var percent = (e.position/ e.totalSize);
// Render a pretty progress bar
};
xhr.onreadystatechange = function(e) {
if(this.readyState === 4) {
// Handle file upload complete
}
};
xhr.open('POST', '/upload', true);
xhr.setRequestHeader('X-FileName',file.name); // Pass the filename along
xhr.send(file);
3
@Gary: Sorry, I should have posted that bit too. I was just using the new drag-and-drop functionality in HTML5; you can find an example here: html5demos.com/file-api#view-source -- just click "view source". Essentially, inside theondrop
event you can dovar file = e.dataTransfer.files[0]
– mpen
Apr 3 '13 at 15:35
Perhaps the question has been edited since, but some people on a let's discussion I opened think a vanilla JS answer is off topic if OP asks for a jQuery solution (provided one exists) and such answers belong with a separate question.
– Andy
Oct 31 '17 at 6:55
2
@Andy Well I disagree, and it seems 34 others do too. If you can use jQuery, then you can certainly use JavaScript. In any case, this is a community site -- it's not just OP that I'm trying to help here. Everyone is free to choose/use the answer they like best. Some people just gravitate towards jQuery because they think it'll be so much easier/fewer lines of code, when really they don't need the overhead of an extra library at all.
– mpen
Oct 31 '17 at 16:20
add a comment |
up vote
41
down vote
You can do it in vanilla JavaScript pretty easily. Here's a snippet from my current project:
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
var percent = (e.position/ e.totalSize);
// Render a pretty progress bar
};
xhr.onreadystatechange = function(e) {
if(this.readyState === 4) {
// Handle file upload complete
}
};
xhr.open('POST', '/upload', true);
xhr.setRequestHeader('X-FileName',file.name); // Pass the filename along
xhr.send(file);
3
@Gary: Sorry, I should have posted that bit too. I was just using the new drag-and-drop functionality in HTML5; you can find an example here: html5demos.com/file-api#view-source -- just click "view source". Essentially, inside theondrop
event you can dovar file = e.dataTransfer.files[0]
– mpen
Apr 3 '13 at 15:35
Perhaps the question has been edited since, but some people on a let's discussion I opened think a vanilla JS answer is off topic if OP asks for a jQuery solution (provided one exists) and such answers belong with a separate question.
– Andy
Oct 31 '17 at 6:55
2
@Andy Well I disagree, and it seems 34 others do too. If you can use jQuery, then you can certainly use JavaScript. In any case, this is a community site -- it's not just OP that I'm trying to help here. Everyone is free to choose/use the answer they like best. Some people just gravitate towards jQuery because they think it'll be so much easier/fewer lines of code, when really they don't need the overhead of an extra library at all.
– mpen
Oct 31 '17 at 16:20
add a comment |
up vote
41
down vote
up vote
41
down vote
You can do it in vanilla JavaScript pretty easily. Here's a snippet from my current project:
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
var percent = (e.position/ e.totalSize);
// Render a pretty progress bar
};
xhr.onreadystatechange = function(e) {
if(this.readyState === 4) {
// Handle file upload complete
}
};
xhr.open('POST', '/upload', true);
xhr.setRequestHeader('X-FileName',file.name); // Pass the filename along
xhr.send(file);
You can do it in vanilla JavaScript pretty easily. Here's a snippet from my current project:
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
var percent = (e.position/ e.totalSize);
// Render a pretty progress bar
};
xhr.onreadystatechange = function(e) {
if(this.readyState === 4) {
// Handle file upload complete
}
};
xhr.open('POST', '/upload', true);
xhr.setRequestHeader('X-FileName',file.name); // Pass the filename along
xhr.send(file);
edited Feb 9 '14 at 10:40
Peter Mortensen
13.4k1983111
13.4k1983111
answered Feb 17 '13 at 9:34
mpen
120k167636932
120k167636932
3
@Gary: Sorry, I should have posted that bit too. I was just using the new drag-and-drop functionality in HTML5; you can find an example here: html5demos.com/file-api#view-source -- just click "view source". Essentially, inside theondrop
event you can dovar file = e.dataTransfer.files[0]
– mpen
Apr 3 '13 at 15:35
Perhaps the question has been edited since, but some people on a let's discussion I opened think a vanilla JS answer is off topic if OP asks for a jQuery solution (provided one exists) and such answers belong with a separate question.
– Andy
Oct 31 '17 at 6:55
2
@Andy Well I disagree, and it seems 34 others do too. If you can use jQuery, then you can certainly use JavaScript. In any case, this is a community site -- it's not just OP that I'm trying to help here. Everyone is free to choose/use the answer they like best. Some people just gravitate towards jQuery because they think it'll be so much easier/fewer lines of code, when really they don't need the overhead of an extra library at all.
– mpen
Oct 31 '17 at 16:20
add a comment |
3
@Gary: Sorry, I should have posted that bit too. I was just using the new drag-and-drop functionality in HTML5; you can find an example here: html5demos.com/file-api#view-source -- just click "view source". Essentially, inside theondrop
event you can dovar file = e.dataTransfer.files[0]
– mpen
Apr 3 '13 at 15:35
Perhaps the question has been edited since, but some people on a let's discussion I opened think a vanilla JS answer is off topic if OP asks for a jQuery solution (provided one exists) and such answers belong with a separate question.
– Andy
Oct 31 '17 at 6:55
2
@Andy Well I disagree, and it seems 34 others do too. If you can use jQuery, then you can certainly use JavaScript. In any case, this is a community site -- it's not just OP that I'm trying to help here. Everyone is free to choose/use the answer they like best. Some people just gravitate towards jQuery because they think it'll be so much easier/fewer lines of code, when really they don't need the overhead of an extra library at all.
– mpen
Oct 31 '17 at 16:20
3
3
@Gary: Sorry, I should have posted that bit too. I was just using the new drag-and-drop functionality in HTML5; you can find an example here: html5demos.com/file-api#view-source -- just click "view source". Essentially, inside the
ondrop
event you can do var file = e.dataTransfer.files[0]
– mpen
Apr 3 '13 at 15:35
@Gary: Sorry, I should have posted that bit too. I was just using the new drag-and-drop functionality in HTML5; you can find an example here: html5demos.com/file-api#view-source -- just click "view source". Essentially, inside the
ondrop
event you can do var file = e.dataTransfer.files[0]
– mpen
Apr 3 '13 at 15:35
Perhaps the question has been edited since, but some people on a let's discussion I opened think a vanilla JS answer is off topic if OP asks for a jQuery solution (provided one exists) and such answers belong with a separate question.
– Andy
Oct 31 '17 at 6:55
Perhaps the question has been edited since, but some people on a let's discussion I opened think a vanilla JS answer is off topic if OP asks for a jQuery solution (provided one exists) and such answers belong with a separate question.
– Andy
Oct 31 '17 at 6:55
2
2
@Andy Well I disagree, and it seems 34 others do too. If you can use jQuery, then you can certainly use JavaScript. In any case, this is a community site -- it's not just OP that I'm trying to help here. Everyone is free to choose/use the answer they like best. Some people just gravitate towards jQuery because they think it'll be so much easier/fewer lines of code, when really they don't need the overhead of an extra library at all.
– mpen
Oct 31 '17 at 16:20
@Andy Well I disagree, and it seems 34 others do too. If you can use jQuery, then you can certainly use JavaScript. In any case, this is a community site -- it's not just OP that I'm trying to help here. Everyone is free to choose/use the answer they like best. Some people just gravitate towards jQuery because they think it'll be so much easier/fewer lines of code, when really they don't need the overhead of an extra library at all.
– mpen
Oct 31 '17 at 16:20
add a comment |
up vote
38
down vote
The simplest and most robust way I have done this in the past, is to simply target a hidden iFrame tag with your form - then it will submit within the iframe without reloading the page.
That is if you don't want to use a plugin, JavaScript or any other forms of "magic" other than HTML. Of course you can combine this with JavaScript or what have you...
<form target="iframe" action="" method="post" enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<iframe name="iframe" id="iframe" style="display:none" ></iframe>
You can also read the contents of the iframe onLoad
for server errors or success responses and then output that to user.
Chrome, iFrames, and onLoad
-note- you only need to keep reading if you are interested in how to setup a UI blocker when doing uploading/downloading
Currently Chrome doesn't trigger the onLoad event for the iframe when it's used to transfer files. Firefox, IE, and Edge all fire the onload event for file transfers.
The only solution that I found works for Chrome was to use a cookie.
To do that basically when the upload/download is started:
- [Client Side] Start an interval to look for the existence of a cookie
- [Server Side] Do whatever you need to with the file data
- [Server Side] Set cookie for client side interval
- [Client Side] Interval sees the cookie and uses it like the onLoad event. For example you can start a UI blocker and then onLoad ( or when cookie is made ) you remove the UI blocker.
Using a cookie for this is ugly but it works.
I made a jQuery plugin to handle this issue for Chrome when downloading, you can find here
https://github.com/ArtisticPhoenix/jQuery-Plugins/blob/master/iDownloader.js
The same basic principal applies to uploading, as well.
To use the downloader ( include the JS, obviously )
$('body').iDownloader({
"onComplete" : function(){
$('#uiBlocker').css('display', 'none'); //hide ui blocker on complete
}
});
$('somebuttion').click( function(){
$('#uiBlocker').css('display', 'block'); //block the UI
$('body').iDownloader('download', 'htttp://example.com/location/of/download');
});
And on the server side, just before transferring the file data, create the cookie
setcookie('iDownloader', true, time() + 30, "/");
The plugin will see the cookie, and then trigger the onComplete
callback.
3
I love it. If only someone could mention the potential problems with this brilliant solution. I really don't understand why people wright and use these clunky libraries and plugins when there is the solution.
– Yevgeniy Afanasyev
Jan 5 '15 at 22:45
1
Well, I guess the reason would be to show some progress info while uploading.
– Prakhar Mishra
Jun 28 '16 at 11:19
add a comment |
up vote
38
down vote
The simplest and most robust way I have done this in the past, is to simply target a hidden iFrame tag with your form - then it will submit within the iframe without reloading the page.
That is if you don't want to use a plugin, JavaScript or any other forms of "magic" other than HTML. Of course you can combine this with JavaScript or what have you...
<form target="iframe" action="" method="post" enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<iframe name="iframe" id="iframe" style="display:none" ></iframe>
You can also read the contents of the iframe onLoad
for server errors or success responses and then output that to user.
Chrome, iFrames, and onLoad
-note- you only need to keep reading if you are interested in how to setup a UI blocker when doing uploading/downloading
Currently Chrome doesn't trigger the onLoad event for the iframe when it's used to transfer files. Firefox, IE, and Edge all fire the onload event for file transfers.
The only solution that I found works for Chrome was to use a cookie.
To do that basically when the upload/download is started:
- [Client Side] Start an interval to look for the existence of a cookie
- [Server Side] Do whatever you need to with the file data
- [Server Side] Set cookie for client side interval
- [Client Side] Interval sees the cookie and uses it like the onLoad event. For example you can start a UI blocker and then onLoad ( or when cookie is made ) you remove the UI blocker.
Using a cookie for this is ugly but it works.
I made a jQuery plugin to handle this issue for Chrome when downloading, you can find here
https://github.com/ArtisticPhoenix/jQuery-Plugins/blob/master/iDownloader.js
The same basic principal applies to uploading, as well.
To use the downloader ( include the JS, obviously )
$('body').iDownloader({
"onComplete" : function(){
$('#uiBlocker').css('display', 'none'); //hide ui blocker on complete
}
});
$('somebuttion').click( function(){
$('#uiBlocker').css('display', 'block'); //block the UI
$('body').iDownloader('download', 'htttp://example.com/location/of/download');
});
And on the server side, just before transferring the file data, create the cookie
setcookie('iDownloader', true, time() + 30, "/");
The plugin will see the cookie, and then trigger the onComplete
callback.
3
I love it. If only someone could mention the potential problems with this brilliant solution. I really don't understand why people wright and use these clunky libraries and plugins when there is the solution.
– Yevgeniy Afanasyev
Jan 5 '15 at 22:45
1
Well, I guess the reason would be to show some progress info while uploading.
– Prakhar Mishra
Jun 28 '16 at 11:19
add a comment |
up vote
38
down vote
up vote
38
down vote
The simplest and most robust way I have done this in the past, is to simply target a hidden iFrame tag with your form - then it will submit within the iframe without reloading the page.
That is if you don't want to use a plugin, JavaScript or any other forms of "magic" other than HTML. Of course you can combine this with JavaScript or what have you...
<form target="iframe" action="" method="post" enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<iframe name="iframe" id="iframe" style="display:none" ></iframe>
You can also read the contents of the iframe onLoad
for server errors or success responses and then output that to user.
Chrome, iFrames, and onLoad
-note- you only need to keep reading if you are interested in how to setup a UI blocker when doing uploading/downloading
Currently Chrome doesn't trigger the onLoad event for the iframe when it's used to transfer files. Firefox, IE, and Edge all fire the onload event for file transfers.
The only solution that I found works for Chrome was to use a cookie.
To do that basically when the upload/download is started:
- [Client Side] Start an interval to look for the existence of a cookie
- [Server Side] Do whatever you need to with the file data
- [Server Side] Set cookie for client side interval
- [Client Side] Interval sees the cookie and uses it like the onLoad event. For example you can start a UI blocker and then onLoad ( or when cookie is made ) you remove the UI blocker.
Using a cookie for this is ugly but it works.
I made a jQuery plugin to handle this issue for Chrome when downloading, you can find here
https://github.com/ArtisticPhoenix/jQuery-Plugins/blob/master/iDownloader.js
The same basic principal applies to uploading, as well.
To use the downloader ( include the JS, obviously )
$('body').iDownloader({
"onComplete" : function(){
$('#uiBlocker').css('display', 'none'); //hide ui blocker on complete
}
});
$('somebuttion').click( function(){
$('#uiBlocker').css('display', 'block'); //block the UI
$('body').iDownloader('download', 'htttp://example.com/location/of/download');
});
And on the server side, just before transferring the file data, create the cookie
setcookie('iDownloader', true, time() + 30, "/");
The plugin will see the cookie, and then trigger the onComplete
callback.
The simplest and most robust way I have done this in the past, is to simply target a hidden iFrame tag with your form - then it will submit within the iframe without reloading the page.
That is if you don't want to use a plugin, JavaScript or any other forms of "magic" other than HTML. Of course you can combine this with JavaScript or what have you...
<form target="iframe" action="" method="post" enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<iframe name="iframe" id="iframe" style="display:none" ></iframe>
You can also read the contents of the iframe onLoad
for server errors or success responses and then output that to user.
Chrome, iFrames, and onLoad
-note- you only need to keep reading if you are interested in how to setup a UI blocker when doing uploading/downloading
Currently Chrome doesn't trigger the onLoad event for the iframe when it's used to transfer files. Firefox, IE, and Edge all fire the onload event for file transfers.
The only solution that I found works for Chrome was to use a cookie.
To do that basically when the upload/download is started:
- [Client Side] Start an interval to look for the existence of a cookie
- [Server Side] Do whatever you need to with the file data
- [Server Side] Set cookie for client side interval
- [Client Side] Interval sees the cookie and uses it like the onLoad event. For example you can start a UI blocker and then onLoad ( or when cookie is made ) you remove the UI blocker.
Using a cookie for this is ugly but it works.
I made a jQuery plugin to handle this issue for Chrome when downloading, you can find here
https://github.com/ArtisticPhoenix/jQuery-Plugins/blob/master/iDownloader.js
The same basic principal applies to uploading, as well.
To use the downloader ( include the JS, obviously )
$('body').iDownloader({
"onComplete" : function(){
$('#uiBlocker').css('display', 'none'); //hide ui blocker on complete
}
});
$('somebuttion').click( function(){
$('#uiBlocker').css('display', 'block'); //block the UI
$('body').iDownloader('download', 'htttp://example.com/location/of/download');
});
And on the server side, just before transferring the file data, create the cookie
setcookie('iDownloader', true, time() + 30, "/");
The plugin will see the cookie, and then trigger the onComplete
callback.
edited Jun 15 at 8:07
tiermix
426
426
answered Jun 26 '14 at 4:43
ArtisticPhoenix
14.8k11223
14.8k11223
3
I love it. If only someone could mention the potential problems with this brilliant solution. I really don't understand why people wright and use these clunky libraries and plugins when there is the solution.
– Yevgeniy Afanasyev
Jan 5 '15 at 22:45
1
Well, I guess the reason would be to show some progress info while uploading.
– Prakhar Mishra
Jun 28 '16 at 11:19
add a comment |
3
I love it. If only someone could mention the potential problems with this brilliant solution. I really don't understand why people wright and use these clunky libraries and plugins when there is the solution.
– Yevgeniy Afanasyev
Jan 5 '15 at 22:45
1
Well, I guess the reason would be to show some progress info while uploading.
– Prakhar Mishra
Jun 28 '16 at 11:19
3
3
I love it. If only someone could mention the potential problems with this brilliant solution. I really don't understand why people wright and use these clunky libraries and plugins when there is the solution.
– Yevgeniy Afanasyev
Jan 5 '15 at 22:45
I love it. If only someone could mention the potential problems with this brilliant solution. I really don't understand why people wright and use these clunky libraries and plugins when there is the solution.
– Yevgeniy Afanasyev
Jan 5 '15 at 22:45
1
1
Well, I guess the reason would be to show some progress info while uploading.
– Prakhar Mishra
Jun 28 '16 at 11:19
Well, I guess the reason would be to show some progress info while uploading.
– Prakhar Mishra
Jun 28 '16 at 11:19
add a comment |
up vote
31
down vote
A solution I found was to have the <form>
target a hidden iFrame. The iFrame can then run JS to display to the user that it's complete (on page load).
This is what jQuery Form does: malsup.com/jquery/form
– Darryl Hein
Sep 15 '14 at 16:59
1
i am interested in this answer, do you have a demo you can link to?
– lfender6445
Jan 30 '15 at 6:37
add a comment |
up vote
31
down vote
A solution I found was to have the <form>
target a hidden iFrame. The iFrame can then run JS to display to the user that it's complete (on page load).
This is what jQuery Form does: malsup.com/jquery/form
– Darryl Hein
Sep 15 '14 at 16:59
1
i am interested in this answer, do you have a demo you can link to?
– lfender6445
Jan 30 '15 at 6:37
add a comment |
up vote
31
down vote
up vote
31
down vote
A solution I found was to have the <form>
target a hidden iFrame. The iFrame can then run JS to display to the user that it's complete (on page load).
A solution I found was to have the <form>
target a hidden iFrame. The iFrame can then run JS to display to the user that it's complete (on page load).
answered Oct 18 '08 at 19:30
Darryl Hein
67.8k83187244
67.8k83187244
This is what jQuery Form does: malsup.com/jquery/form
– Darryl Hein
Sep 15 '14 at 16:59
1
i am interested in this answer, do you have a demo you can link to?
– lfender6445
Jan 30 '15 at 6:37
add a comment |
This is what jQuery Form does: malsup.com/jquery/form
– Darryl Hein
Sep 15 '14 at 16:59
1
i am interested in this answer, do you have a demo you can link to?
– lfender6445
Jan 30 '15 at 6:37
This is what jQuery Form does: malsup.com/jquery/form
– Darryl Hein
Sep 15 '14 at 16:59
This is what jQuery Form does: malsup.com/jquery/form
– Darryl Hein
Sep 15 '14 at 16:59
1
1
i am interested in this answer, do you have a demo you can link to?
– lfender6445
Jan 30 '15 at 6:37
i am interested in this answer, do you have a demo you can link to?
– lfender6445
Jan 30 '15 at 6:37
add a comment |
up vote
30
down vote
I've written this up in a Rails environment. It's only about five lines of JavaScript, if you use the lightweight jQuery-form plugin.
The challenge is in getting AJAX upload working as the standard remote_form_for
doesn't understand multi-part form submission. It's not going to send the file data Rails seeks back with the AJAX request.
That's where the jQuery-form plugin comes into play.
Here’s the Rails code for it:
<% remote_form_for(:image_form,
:url => { :controller => "blogs", :action => :create_asset },
:html => { :method => :post,
:id => 'uploadForm', :multipart => true })
do |f| %>
Upload a file: <%= f.file_field :uploaded_data %>
<% end %>
Here’s the associated JavaScript:
$('#uploadForm input').change(function(){
$(this).parent().ajaxSubmit({
beforeSubmit: function(a,f,o) {
o.dataType = 'json';
},
complete: function(XMLHttpRequest, textStatus) {
// XMLHttpRequest.responseText will contain the URL of the uploaded image.
// Put it in an image element you create, or do with it what you will.
// For example, if you have an image elemtn with id "my_image", then
// $('#my_image').attr('src', XMLHttpRequest.responseText);
// Will set that image tag to display the uploaded image.
},
});
});
And here’s the Rails controller action, pretty vanilla:
@image = Image.new(params[:image_form])
@image.save
render :text => @image.public_filename
I’ve been using this for the past few weeks with Bloggity, and it’s worked like a champ.
add a comment |
up vote
30
down vote
I've written this up in a Rails environment. It's only about five lines of JavaScript, if you use the lightweight jQuery-form plugin.
The challenge is in getting AJAX upload working as the standard remote_form_for
doesn't understand multi-part form submission. It's not going to send the file data Rails seeks back with the AJAX request.
That's where the jQuery-form plugin comes into play.
Here’s the Rails code for it:
<% remote_form_for(:image_form,
:url => { :controller => "blogs", :action => :create_asset },
:html => { :method => :post,
:id => 'uploadForm', :multipart => true })
do |f| %>
Upload a file: <%= f.file_field :uploaded_data %>
<% end %>
Here’s the associated JavaScript:
$('#uploadForm input').change(function(){
$(this).parent().ajaxSubmit({
beforeSubmit: function(a,f,o) {
o.dataType = 'json';
},
complete: function(XMLHttpRequest, textStatus) {
// XMLHttpRequest.responseText will contain the URL of the uploaded image.
// Put it in an image element you create, or do with it what you will.
// For example, if you have an image elemtn with id "my_image", then
// $('#my_image').attr('src', XMLHttpRequest.responseText);
// Will set that image tag to display the uploaded image.
},
});
});
And here’s the Rails controller action, pretty vanilla:
@image = Image.new(params[:image_form])
@image.save
render :text => @image.public_filename
I’ve been using this for the past few weeks with Bloggity, and it’s worked like a champ.
add a comment |
up vote
30
down vote
up vote
30
down vote
I've written this up in a Rails environment. It's only about five lines of JavaScript, if you use the lightweight jQuery-form plugin.
The challenge is in getting AJAX upload working as the standard remote_form_for
doesn't understand multi-part form submission. It's not going to send the file data Rails seeks back with the AJAX request.
That's where the jQuery-form plugin comes into play.
Here’s the Rails code for it:
<% remote_form_for(:image_form,
:url => { :controller => "blogs", :action => :create_asset },
:html => { :method => :post,
:id => 'uploadForm', :multipart => true })
do |f| %>
Upload a file: <%= f.file_field :uploaded_data %>
<% end %>
Here’s the associated JavaScript:
$('#uploadForm input').change(function(){
$(this).parent().ajaxSubmit({
beforeSubmit: function(a,f,o) {
o.dataType = 'json';
},
complete: function(XMLHttpRequest, textStatus) {
// XMLHttpRequest.responseText will contain the URL of the uploaded image.
// Put it in an image element you create, or do with it what you will.
// For example, if you have an image elemtn with id "my_image", then
// $('#my_image').attr('src', XMLHttpRequest.responseText);
// Will set that image tag to display the uploaded image.
},
});
});
And here’s the Rails controller action, pretty vanilla:
@image = Image.new(params[:image_form])
@image.save
render :text => @image.public_filename
I’ve been using this for the past few weeks with Bloggity, and it’s worked like a champ.
I've written this up in a Rails environment. It's only about five lines of JavaScript, if you use the lightweight jQuery-form plugin.
The challenge is in getting AJAX upload working as the standard remote_form_for
doesn't understand multi-part form submission. It's not going to send the file data Rails seeks back with the AJAX request.
That's where the jQuery-form plugin comes into play.
Here’s the Rails code for it:
<% remote_form_for(:image_form,
:url => { :controller => "blogs", :action => :create_asset },
:html => { :method => :post,
:id => 'uploadForm', :multipart => true })
do |f| %>
Upload a file: <%= f.file_field :uploaded_data %>
<% end %>
Here’s the associated JavaScript:
$('#uploadForm input').change(function(){
$(this).parent().ajaxSubmit({
beforeSubmit: function(a,f,o) {
o.dataType = 'json';
},
complete: function(XMLHttpRequest, textStatus) {
// XMLHttpRequest.responseText will contain the URL of the uploaded image.
// Put it in an image element you create, or do with it what you will.
// For example, if you have an image elemtn with id "my_image", then
// $('#my_image').attr('src', XMLHttpRequest.responseText);
// Will set that image tag to display the uploaded image.
},
});
});
And here’s the Rails controller action, pretty vanilla:
@image = Image.new(params[:image_form])
@image.save
render :text => @image.public_filename
I’ve been using this for the past few weeks with Bloggity, and it’s worked like a champ.
edited Oct 8 '11 at 18:57
random
8,08175573
8,08175573
answered Aug 13 '09 at 22:44
wbharding
1,27521517
1,27521517
add a comment |
add a comment |
up vote
29
down vote
Simple Ajax Uploader is another option:
https://github.com/LPology/Simple-Ajax-Uploader
- Cross-browser -- works in IE7+, Firefox, Chrome, Safari, Opera
- Supports multiple, concurrent uploads -- even in non-HTML5 browsers
- No flash or external CSS -- just one 5Kb Javascript file
- Optional, built-in support for fully cross-browser progress bars (using PHP's APC extension)
- Flexible and highly customizable -- use any element as upload button, style your own progress indicators
- No forms required, just provide an element that will serve as upload button
- MIT license -- free to use in commercial project
Example usage:
var uploader = new ss.SimpleUpload({
button: $('#uploadBtn'), // upload button
url: '/uploadhandler', // URL of server-side upload handler
name: 'userfile', // parameter name of the uploaded file
onSubmit: function() {
this.setProgressBar( $('#progressBar') ); // designate elem as our progress bar
},
onComplete: function(file, response) {
// do whatever after upload is finished
}
});
2
This seems to be the most promising so far, You had me atIE7+
! Trying it out now. Thanks
– Pierre
Jun 28 '14 at 10:53
add a comment |
up vote
29
down vote
Simple Ajax Uploader is another option:
https://github.com/LPology/Simple-Ajax-Uploader
- Cross-browser -- works in IE7+, Firefox, Chrome, Safari, Opera
- Supports multiple, concurrent uploads -- even in non-HTML5 browsers
- No flash or external CSS -- just one 5Kb Javascript file
- Optional, built-in support for fully cross-browser progress bars (using PHP's APC extension)
- Flexible and highly customizable -- use any element as upload button, style your own progress indicators
- No forms required, just provide an element that will serve as upload button
- MIT license -- free to use in commercial project
Example usage:
var uploader = new ss.SimpleUpload({
button: $('#uploadBtn'), // upload button
url: '/uploadhandler', // URL of server-side upload handler
name: 'userfile', // parameter name of the uploaded file
onSubmit: function() {
this.setProgressBar( $('#progressBar') ); // designate elem as our progress bar
},
onComplete: function(file, response) {
// do whatever after upload is finished
}
});
2
This seems to be the most promising so far, You had me atIE7+
! Trying it out now. Thanks
– Pierre
Jun 28 '14 at 10:53
add a comment |
up vote
29
down vote
up vote
29
down vote
Simple Ajax Uploader is another option:
https://github.com/LPology/Simple-Ajax-Uploader
- Cross-browser -- works in IE7+, Firefox, Chrome, Safari, Opera
- Supports multiple, concurrent uploads -- even in non-HTML5 browsers
- No flash or external CSS -- just one 5Kb Javascript file
- Optional, built-in support for fully cross-browser progress bars (using PHP's APC extension)
- Flexible and highly customizable -- use any element as upload button, style your own progress indicators
- No forms required, just provide an element that will serve as upload button
- MIT license -- free to use in commercial project
Example usage:
var uploader = new ss.SimpleUpload({
button: $('#uploadBtn'), // upload button
url: '/uploadhandler', // URL of server-side upload handler
name: 'userfile', // parameter name of the uploaded file
onSubmit: function() {
this.setProgressBar( $('#progressBar') ); // designate elem as our progress bar
},
onComplete: function(file, response) {
// do whatever after upload is finished
}
});
Simple Ajax Uploader is another option:
https://github.com/LPology/Simple-Ajax-Uploader
- Cross-browser -- works in IE7+, Firefox, Chrome, Safari, Opera
- Supports multiple, concurrent uploads -- even in non-HTML5 browsers
- No flash or external CSS -- just one 5Kb Javascript file
- Optional, built-in support for fully cross-browser progress bars (using PHP's APC extension)
- Flexible and highly customizable -- use any element as upload button, style your own progress indicators
- No forms required, just provide an element that will serve as upload button
- MIT license -- free to use in commercial project
Example usage:
var uploader = new ss.SimpleUpload({
button: $('#uploadBtn'), // upload button
url: '/uploadhandler', // URL of server-side upload handler
name: 'userfile', // parameter name of the uploaded file
onSubmit: function() {
this.setProgressBar( $('#progressBar') ); // designate elem as our progress bar
},
onComplete: function(file, response) {
// do whatever after upload is finished
}
});
edited Jun 26 '13 at 1:37
answered Jun 26 '13 at 1:12
user1091949
1,22321726
1,22321726
2
This seems to be the most promising so far, You had me atIE7+
! Trying it out now. Thanks
– Pierre
Jun 28 '14 at 10:53
add a comment |
2
This seems to be the most promising so far, You had me atIE7+
! Trying it out now. Thanks
– Pierre
Jun 28 '14 at 10:53
2
2
This seems to be the most promising so far, You had me at
IE7+
! Trying it out now. Thanks– Pierre
Jun 28 '14 at 10:53
This seems to be the most promising so far, You had me at
IE7+
! Trying it out now. Thanks– Pierre
Jun 28 '14 at 10:53
add a comment |
up vote
21
down vote
jQuery Uploadify is another good plugin which I have used before to upload files. The JavaScript code is as simple as the following: code. However, the new version does not work in Internet Explorer.
$('#file_upload').uploadify({
'swf': '/public/js/uploadify.swf',
'uploader': '/Upload.ashx?formGuid=' + $('#formGuid').val(),
'cancelImg': '/public/images/uploadify-cancel.png',
'multi': true,
'onQueueComplete': function (queueData) {
// ...
},
'onUploadStart': function (file) {
// ...
}
});
I have done a lot of searching and I have come to another solution for uploading files without any plugin and only with ajax. The solution is as below:
$(document).ready(function () {
$('#btn_Upload').live('click', AjaxFileUpload);
});
function AjaxFileUpload() {
var fileInput = document.getElementById("#Uploader");
var file = fileInput.files[0];
var fd = new FormData();
fd.append("files", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", 'Uploader.ashx');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert('success');
}
else if (uploadResult == 'success')
alert('error');
};
xhr.send(fd);
}
2
Uploadify has been dead for years. Not supported or maintained anymore.
– Ray Nicholus
Jun 8 '16 at 17:44
add a comment |
up vote
21
down vote
jQuery Uploadify is another good plugin which I have used before to upload files. The JavaScript code is as simple as the following: code. However, the new version does not work in Internet Explorer.
$('#file_upload').uploadify({
'swf': '/public/js/uploadify.swf',
'uploader': '/Upload.ashx?formGuid=' + $('#formGuid').val(),
'cancelImg': '/public/images/uploadify-cancel.png',
'multi': true,
'onQueueComplete': function (queueData) {
// ...
},
'onUploadStart': function (file) {
// ...
}
});
I have done a lot of searching and I have come to another solution for uploading files without any plugin and only with ajax. The solution is as below:
$(document).ready(function () {
$('#btn_Upload').live('click', AjaxFileUpload);
});
function AjaxFileUpload() {
var fileInput = document.getElementById("#Uploader");
var file = fileInput.files[0];
var fd = new FormData();
fd.append("files", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", 'Uploader.ashx');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert('success');
}
else if (uploadResult == 'success')
alert('error');
};
xhr.send(fd);
}
2
Uploadify has been dead for years. Not supported or maintained anymore.
– Ray Nicholus
Jun 8 '16 at 17:44
add a comment |
up vote
21
down vote
up vote
21
down vote
jQuery Uploadify is another good plugin which I have used before to upload files. The JavaScript code is as simple as the following: code. However, the new version does not work in Internet Explorer.
$('#file_upload').uploadify({
'swf': '/public/js/uploadify.swf',
'uploader': '/Upload.ashx?formGuid=' + $('#formGuid').val(),
'cancelImg': '/public/images/uploadify-cancel.png',
'multi': true,
'onQueueComplete': function (queueData) {
// ...
},
'onUploadStart': function (file) {
// ...
}
});
I have done a lot of searching and I have come to another solution for uploading files without any plugin and only with ajax. The solution is as below:
$(document).ready(function () {
$('#btn_Upload').live('click', AjaxFileUpload);
});
function AjaxFileUpload() {
var fileInput = document.getElementById("#Uploader");
var file = fileInput.files[0];
var fd = new FormData();
fd.append("files", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", 'Uploader.ashx');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert('success');
}
else if (uploadResult == 'success')
alert('error');
};
xhr.send(fd);
}
jQuery Uploadify is another good plugin which I have used before to upload files. The JavaScript code is as simple as the following: code. However, the new version does not work in Internet Explorer.
$('#file_upload').uploadify({
'swf': '/public/js/uploadify.swf',
'uploader': '/Upload.ashx?formGuid=' + $('#formGuid').val(),
'cancelImg': '/public/images/uploadify-cancel.png',
'multi': true,
'onQueueComplete': function (queueData) {
// ...
},
'onUploadStart': function (file) {
// ...
}
});
I have done a lot of searching and I have come to another solution for uploading files without any plugin and only with ajax. The solution is as below:
$(document).ready(function () {
$('#btn_Upload').live('click', AjaxFileUpload);
});
function AjaxFileUpload() {
var fileInput = document.getElementById("#Uploader");
var file = fileInput.files[0];
var fd = new FormData();
fd.append("files", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", 'Uploader.ashx');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert('success');
}
else if (uploadResult == 'success')
alert('error');
};
xhr.send(fd);
}
edited Apr 10 '14 at 14:18
ivan_pozdeev
18.4k74689
18.4k74689
answered Jun 16 '13 at 9:49
farnoush resa
33337
33337
2
Uploadify has been dead for years. Not supported or maintained anymore.
– Ray Nicholus
Jun 8 '16 at 17:44
add a comment |
2
Uploadify has been dead for years. Not supported or maintained anymore.
– Ray Nicholus
Jun 8 '16 at 17:44
2
2
Uploadify has been dead for years. Not supported or maintained anymore.
– Ray Nicholus
Jun 8 '16 at 17:44
Uploadify has been dead for years. Not supported or maintained anymore.
– Ray Nicholus
Jun 8 '16 at 17:44
add a comment |
up vote
20
down vote
Here's just another solution of how to upload file (without any plugin)
Using simple Javascripts and AJAX (with progress-bar)
HTML part
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
JS part
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
PHP part
<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){ // assuming the directory name 'test_uploads'
echo "$fileName upload is complete";
} else {
echo "move_uploaded_file function failed";
}
?>
Here's the EXAMPLE application
Does not work with IE9.
– Zameer Fouzan
Jan 31 at 14:16
add a comment |
up vote
20
down vote
Here's just another solution of how to upload file (without any plugin)
Using simple Javascripts and AJAX (with progress-bar)
HTML part
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
JS part
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
PHP part
<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){ // assuming the directory name 'test_uploads'
echo "$fileName upload is complete";
} else {
echo "move_uploaded_file function failed";
}
?>
Here's the EXAMPLE application
Does not work with IE9.
– Zameer Fouzan
Jan 31 at 14:16
add a comment |
up vote
20
down vote
up vote
20
down vote
Here's just another solution of how to upload file (without any plugin)
Using simple Javascripts and AJAX (with progress-bar)
HTML part
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
JS part
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
PHP part
<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){ // assuming the directory name 'test_uploads'
echo "$fileName upload is complete";
} else {
echo "move_uploaded_file function failed";
}
?>
Here's the EXAMPLE application
Here's just another solution of how to upload file (without any plugin)
Using simple Javascripts and AJAX (with progress-bar)
HTML part
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
JS part
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
PHP part
<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){ // assuming the directory name 'test_uploads'
echo "$fileName upload is complete";
} else {
echo "move_uploaded_file function failed";
}
?>
Here's the EXAMPLE application
edited Jul 24 '16 at 14:02
answered Mar 30 '16 at 16:48
Siddhartha Chowdhury
1,286922
1,286922
Does not work with IE9.
– Zameer Fouzan
Jan 31 at 14:16
add a comment |
Does not work with IE9.
– Zameer Fouzan
Jan 31 at 14:16
Does not work with IE9.
– Zameer Fouzan
Jan 31 at 14:16
Does not work with IE9.
– Zameer Fouzan
Jan 31 at 14:16
add a comment |
up vote
15
down vote
var formData=new FormData();
formData.append("fieldname","value");
formData.append("image",$('[name="filename"]')[0].files[0]);
$.ajax({
url:"page.php",
data:formData,
type: 'POST',
dataType:"JSON",
cache: false,
contentType: false,
processData: false,
success:function(data){ }
});
You can use form data to post all your values including images.
6
Note:cache: false
is redundant on aPOST
request asPOST
never caches.
– Gone Coding
Aug 10 '15 at 9:10
@Vivek Aasaithambi, I got this error:TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
– candlejack
Dec 25 '16 at 23:28
add a comment |
up vote
15
down vote
var formData=new FormData();
formData.append("fieldname","value");
formData.append("image",$('[name="filename"]')[0].files[0]);
$.ajax({
url:"page.php",
data:formData,
type: 'POST',
dataType:"JSON",
cache: false,
contentType: false,
processData: false,
success:function(data){ }
});
You can use form data to post all your values including images.
6
Note:cache: false
is redundant on aPOST
request asPOST
never caches.
– Gone Coding
Aug 10 '15 at 9:10
@Vivek Aasaithambi, I got this error:TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
– candlejack
Dec 25 '16 at 23:28
add a comment |
up vote
15
down vote
up vote
15
down vote
var formData=new FormData();
formData.append("fieldname","value");
formData.append("image",$('[name="filename"]')[0].files[0]);
$.ajax({
url:"page.php",
data:formData,
type: 'POST',
dataType:"JSON",
cache: false,
contentType: false,
processData: false,
success:function(data){ }
});
You can use form data to post all your values including images.
var formData=new FormData();
formData.append("fieldname","value");
formData.append("image",$('[name="filename"]')[0].files[0]);
$.ajax({
url:"page.php",
data:formData,
type: 'POST',
dataType:"JSON",
cache: false,
contentType: false,
processData: false,
success:function(data){ }
});
You can use form data to post all your values including images.
edited Dec 22 '15 at 17:01
falsarella
9,58245193
9,58245193
answered Jul 28 '15 at 13:39
Vivek Aasaithambi
692619
692619
6
Note:cache: false
is redundant on aPOST
request asPOST
never caches.
– Gone Coding
Aug 10 '15 at 9:10
@Vivek Aasaithambi, I got this error:TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
– candlejack
Dec 25 '16 at 23:28
add a comment |
6
Note:cache: false
is redundant on aPOST
request asPOST
never caches.
– Gone Coding
Aug 10 '15 at 9:10
@Vivek Aasaithambi, I got this error:TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
– candlejack
Dec 25 '16 at 23:28
6
6
Note:
cache: false
is redundant on a POST
request as POST
never caches.– Gone Coding
Aug 10 '15 at 9:10
Note:
cache: false
is redundant on a POST
request as POST
never caches.– Gone Coding
Aug 10 '15 at 9:10
@Vivek Aasaithambi, I got this error:
TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
– candlejack
Dec 25 '16 at 23:28
@Vivek Aasaithambi, I got this error:
TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
– candlejack
Dec 25 '16 at 23:28
add a comment |
up vote
12
down vote
To upload file asynchronously with Jquery use below steps:
step 1 In your project open Nuget manager and add package (jquery fileupload(only you need to write it in search box it will come up and install it.))
URL: https://github.com/blueimp/jQuery-File-Upload
step 2 Add below scripts in the HTML files, which are already added to the project by running above package:
jquery.ui.widget.js
jquery.iframe-transport.js
jquery.fileupload.js
step 3 Write file upload control as per below code:
<input id="upload" name="upload" type="file" />
step 4 write a js method as uploadFile as below:
function uploadFile(element) {
$(element).fileupload({
dataType: 'json',
url: '../DocumentUpload/upload',
autoUpload: true,
add: function (e, data) {
// write code for implementing, while selecting a file.
// data represents the file data.
//below code triggers the action in mvc controller
data.formData =
{
files: data.files[0]
};
data.submit();
},
done: function (e, data) {
// after file uploaded
},
progress: function (e, data) {
// progress
},
fail: function (e, data) {
//fail operation
},
stop: function () {
code for cancel operation
}
});
};
step 5 In ready function call element file upload to initiate the process as per below:
$(document).ready(function()
{
uploadFile($('#upload'));
});
step 6 Write MVC controller and Action as per below:
public class DocumentUploadController : Controller
{
[System.Web.Mvc.HttpPost]
public JsonResult upload(ICollection<HttpPostedFileBase> files)
{
bool result = false;
if (files != null || files.Count > 0)
{
try
{
foreach (HttpPostedFileBase file in files)
{
if (file.ContentLength == 0)
throw new Exception("Zero length file!");
else
//code for saving a file
}
}
catch (Exception)
{
result = false;
}
}
return new JsonResult()
{
Data=result
};
}
}
add a comment |
up vote
12
down vote
To upload file asynchronously with Jquery use below steps:
step 1 In your project open Nuget manager and add package (jquery fileupload(only you need to write it in search box it will come up and install it.))
URL: https://github.com/blueimp/jQuery-File-Upload
step 2 Add below scripts in the HTML files, which are already added to the project by running above package:
jquery.ui.widget.js
jquery.iframe-transport.js
jquery.fileupload.js
step 3 Write file upload control as per below code:
<input id="upload" name="upload" type="file" />
step 4 write a js method as uploadFile as below:
function uploadFile(element) {
$(element).fileupload({
dataType: 'json',
url: '../DocumentUpload/upload',
autoUpload: true,
add: function (e, data) {
// write code for implementing, while selecting a file.
// data represents the file data.
//below code triggers the action in mvc controller
data.formData =
{
files: data.files[0]
};
data.submit();
},
done: function (e, data) {
// after file uploaded
},
progress: function (e, data) {
// progress
},
fail: function (e, data) {
//fail operation
},
stop: function () {
code for cancel operation
}
});
};
step 5 In ready function call element file upload to initiate the process as per below:
$(document).ready(function()
{
uploadFile($('#upload'));
});
step 6 Write MVC controller and Action as per below:
public class DocumentUploadController : Controller
{
[System.Web.Mvc.HttpPost]
public JsonResult upload(ICollection<HttpPostedFileBase> files)
{
bool result = false;
if (files != null || files.Count > 0)
{
try
{
foreach (HttpPostedFileBase file in files)
{
if (file.ContentLength == 0)
throw new Exception("Zero length file!");
else
//code for saving a file
}
}
catch (Exception)
{
result = false;
}
}
return new JsonResult()
{
Data=result
};
}
}
add a comment |
up vote
12
down vote
up vote
12
down vote
To upload file asynchronously with Jquery use below steps:
step 1 In your project open Nuget manager and add package (jquery fileupload(only you need to write it in search box it will come up and install it.))
URL: https://github.com/blueimp/jQuery-File-Upload
step 2 Add below scripts in the HTML files, which are already added to the project by running above package:
jquery.ui.widget.js
jquery.iframe-transport.js
jquery.fileupload.js
step 3 Write file upload control as per below code:
<input id="upload" name="upload" type="file" />
step 4 write a js method as uploadFile as below:
function uploadFile(element) {
$(element).fileupload({
dataType: 'json',
url: '../DocumentUpload/upload',
autoUpload: true,
add: function (e, data) {
// write code for implementing, while selecting a file.
// data represents the file data.
//below code triggers the action in mvc controller
data.formData =
{
files: data.files[0]
};
data.submit();
},
done: function (e, data) {
// after file uploaded
},
progress: function (e, data) {
// progress
},
fail: function (e, data) {
//fail operation
},
stop: function () {
code for cancel operation
}
});
};
step 5 In ready function call element file upload to initiate the process as per below:
$(document).ready(function()
{
uploadFile($('#upload'));
});
step 6 Write MVC controller and Action as per below:
public class DocumentUploadController : Controller
{
[System.Web.Mvc.HttpPost]
public JsonResult upload(ICollection<HttpPostedFileBase> files)
{
bool result = false;
if (files != null || files.Count > 0)
{
try
{
foreach (HttpPostedFileBase file in files)
{
if (file.ContentLength == 0)
throw new Exception("Zero length file!");
else
//code for saving a file
}
}
catch (Exception)
{
result = false;
}
}
return new JsonResult()
{
Data=result
};
}
}
To upload file asynchronously with Jquery use below steps:
step 1 In your project open Nuget manager and add package (jquery fileupload(only you need to write it in search box it will come up and install it.))
URL: https://github.com/blueimp/jQuery-File-Upload
step 2 Add below scripts in the HTML files, which are already added to the project by running above package:
jquery.ui.widget.js
jquery.iframe-transport.js
jquery.fileupload.js
step 3 Write file upload control as per below code:
<input id="upload" name="upload" type="file" />
step 4 write a js method as uploadFile as below:
function uploadFile(element) {
$(element).fileupload({
dataType: 'json',
url: '../DocumentUpload/upload',
autoUpload: true,
add: function (e, data) {
// write code for implementing, while selecting a file.
// data represents the file data.
//below code triggers the action in mvc controller
data.formData =
{
files: data.files[0]
};
data.submit();
},
done: function (e, data) {
// after file uploaded
},
progress: function (e, data) {
// progress
},
fail: function (e, data) {
//fail operation
},
stop: function () {
code for cancel operation
}
});
};
step 5 In ready function call element file upload to initiate the process as per below:
$(document).ready(function()
{
uploadFile($('#upload'));
});
step 6 Write MVC controller and Action as per below:
public class DocumentUploadController : Controller
{
[System.Web.Mvc.HttpPost]
public JsonResult upload(ICollection<HttpPostedFileBase> files)
{
bool result = false;
if (files != null || files.Count > 0)
{
try
{
foreach (HttpPostedFileBase file in files)
{
if (file.ContentLength == 0)
throw new Exception("Zero length file!");
else
//code for saving a file
}
}
catch (Exception)
{
result = false;
}
}
return new JsonResult()
{
Data=result
};
}
}
edited Jul 9 '14 at 4:52
Majid Golshadi
2,10221526
2,10221526
answered Jun 23 '14 at 8:18
ashish
19713
19713
add a comment |
add a comment |
up vote
8
down vote
Convert file to base64 using |HTML5's readAsDataURL() or some base64 encoder.
Fiddle here
var reader = new FileReader();
reader.onload = function(readerEvt) {
var binaryString = readerEvt.target.result;
document.getElementById("base64textarea").value = btoa(binaryString);
};
reader.readAsBinaryString(file);
Then to retrieve:
window.open("data:application/octet-stream;base64," + base64);
add a comment |
up vote
8
down vote
Convert file to base64 using |HTML5's readAsDataURL() or some base64 encoder.
Fiddle here
var reader = new FileReader();
reader.onload = function(readerEvt) {
var binaryString = readerEvt.target.result;
document.getElementById("base64textarea").value = btoa(binaryString);
};
reader.readAsBinaryString(file);
Then to retrieve:
window.open("data:application/octet-stream;base64," + base64);
add a comment |
up vote
8
down vote
up vote
8
down vote
Convert file to base64 using |HTML5's readAsDataURL() or some base64 encoder.
Fiddle here
var reader = new FileReader();
reader.onload = function(readerEvt) {
var binaryString = readerEvt.target.result;
document.getElementById("base64textarea").value = btoa(binaryString);
};
reader.readAsBinaryString(file);
Then to retrieve:
window.open("data:application/octet-stream;base64," + base64);
Convert file to base64 using |HTML5's readAsDataURL() or some base64 encoder.
Fiddle here
var reader = new FileReader();
reader.onload = function(readerEvt) {
var binaryString = readerEvt.target.result;
document.getElementById("base64textarea").value = btoa(binaryString);
};
reader.readAsBinaryString(file);
Then to retrieve:
window.open("data:application/octet-stream;base64," + base64);
answered Jun 23 '14 at 18:50
tnt-rox
3,97922543
3,97922543
add a comment |
add a comment |
up vote
8
down vote
You can see a solved solution with a working demo here that allows you to preview and submit form files to the server. For your case, you need to use Ajax to facilitate the file upload to the server:
<from action="" id="formContent" method="post" enctype="multipart/form-data">
<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>
</form>
The data being submitted is a formdata. On your jQuery, use a form submit function instead of a button click to submit the form file as shown below.
$(document).ready(function () {
$("#formContent").submit(function(e){
e.preventDefault();
var formdata = new FormData(this);
$.ajax({
url: "ajax_upload_image.php",
type: "POST",
data: formdata,
mimeTypes:"multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(){
alert("successfully submitted");
});
});
});
View more details
add a comment |
up vote
8
down vote
You can see a solved solution with a working demo here that allows you to preview and submit form files to the server. For your case, you need to use Ajax to facilitate the file upload to the server:
<from action="" id="formContent" method="post" enctype="multipart/form-data">
<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>
</form>
The data being submitted is a formdata. On your jQuery, use a form submit function instead of a button click to submit the form file as shown below.
$(document).ready(function () {
$("#formContent").submit(function(e){
e.preventDefault();
var formdata = new FormData(this);
$.ajax({
url: "ajax_upload_image.php",
type: "POST",
data: formdata,
mimeTypes:"multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(){
alert("successfully submitted");
});
});
});
View more details
add a comment |
up vote
8
down vote
up vote
8
down vote
You can see a solved solution with a working demo here that allows you to preview and submit form files to the server. For your case, you need to use Ajax to facilitate the file upload to the server:
<from action="" id="formContent" method="post" enctype="multipart/form-data">
<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>
</form>
The data being submitted is a formdata. On your jQuery, use a form submit function instead of a button click to submit the form file as shown below.
$(document).ready(function () {
$("#formContent").submit(function(e){
e.preventDefault();
var formdata = new FormData(this);
$.ajax({
url: "ajax_upload_image.php",
type: "POST",
data: formdata,
mimeTypes:"multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(){
alert("successfully submitted");
});
});
});
View more details
You can see a solved solution with a working demo here that allows you to preview and submit form files to the server. For your case, you need to use Ajax to facilitate the file upload to the server:
<from action="" id="formContent" method="post" enctype="multipart/form-data">
<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>
</form>
The data being submitted is a formdata. On your jQuery, use a form submit function instead of a button click to submit the form file as shown below.
$(document).ready(function () {
$("#formContent").submit(function(e){
e.preventDefault();
var formdata = new FormData(this);
$.ajax({
url: "ajax_upload_image.php",
type: "POST",
data: formdata,
mimeTypes:"multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(){
alert("successfully submitted");
});
});
});
View more details
edited Dec 17 '16 at 13:09
Peter Mortensen
13.4k1983111
13.4k1983111
answered Jul 19 '16 at 5:18
Daniel Nyamasyo
1,0071016
1,0071016
add a comment |
add a comment |
up vote
8
down vote
Sample: If you use jQuery, you can do easy to an upload file. This is a small and strong jQuery plugin, http://jquery.malsup.com/form/.
Example
var $bar = $('.ProgressBar');
$('.Form').ajaxForm({
dataType: 'json',
beforeSend: function(xhr) {
var percentVal = '0%';
$bar.width(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
$bar.width(percentVal)
},
success: function(response) {
// Response
}
});
I hope it would be helpful
add a comment |
up vote
8
down vote
Sample: If you use jQuery, you can do easy to an upload file. This is a small and strong jQuery plugin, http://jquery.malsup.com/form/.
Example
var $bar = $('.ProgressBar');
$('.Form').ajaxForm({
dataType: 'json',
beforeSend: function(xhr) {
var percentVal = '0%';
$bar.width(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
$bar.width(percentVal)
},
success: function(response) {
// Response
}
});
I hope it would be helpful
add a comment |
up vote
8
down vote
up vote
8
down vote
Sample: If you use jQuery, you can do easy to an upload file. This is a small and strong jQuery plugin, http://jquery.malsup.com/form/.
Example
var $bar = $('.ProgressBar');
$('.Form').ajaxForm({
dataType: 'json',
beforeSend: function(xhr) {
var percentVal = '0%';
$bar.width(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
$bar.width(percentVal)
},
success: function(response) {
// Response
}
});
I hope it would be helpful
Sample: If you use jQuery, you can do easy to an upload file. This is a small and strong jQuery plugin, http://jquery.malsup.com/form/.
Example
var $bar = $('.ProgressBar');
$('.Form').ajaxForm({
dataType: 'json',
beforeSend: function(xhr) {
var percentVal = '0%';
$bar.width(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
$bar.width(percentVal)
},
success: function(response) {
// Response
}
});
I hope it would be helpful
edited Dec 17 '16 at 13:10
Peter Mortensen
13.4k1983111
13.4k1983111
answered Oct 14 '16 at 7:17
MEAbid
37358
37358
add a comment |
add a comment |
up vote
7
down vote
You can use
$(function() {
$("#file_upload_1").uploadify({
height : 30,
swf : '/uploadify/uploadify.swf',
uploader : '/uploadify/uploadify.php',
width : 120
});
});
Demo
add a comment |
up vote
7
down vote
You can use
$(function() {
$("#file_upload_1").uploadify({
height : 30,
swf : '/uploadify/uploadify.swf',
uploader : '/uploadify/uploadify.php',
width : 120
});
});
Demo
add a comment |
up vote
7
down vote
up vote
7
down vote
You can use
$(function() {
$("#file_upload_1").uploadify({
height : 30,
swf : '/uploadify/uploadify.swf',
uploader : '/uploadify/uploadify.php',
width : 120
});
});
Demo
You can use
$(function() {
$("#file_upload_1").uploadify({
height : 30,
swf : '/uploadify/uploadify.swf',
uploader : '/uploadify/uploadify.php',
width : 120
});
});
Demo
answered May 12 '14 at 10:10
Amit
1,1691025
1,1691025
add a comment |
add a comment |
up vote
7
down vote
A modern approach without Jquery is to use the FileList object you get back from <input type="file">
when user selects a file(s) and then use Fetch to post the FileList wrapped around a FormData object.
// The input DOM element
const inputElement = document.querySelector('input');
// Listen for a file submit from user
inputElement.addEventListener('change', () => {
const data = new FormData();
data.append('file', inputElement.files[0]);
data.append('imageName', 'flower');
// Post to server
fetch('/uploadImage', {
method: 'POST',
body: data
});
});
add a comment |
up vote
7
down vote
A modern approach without Jquery is to use the FileList object you get back from <input type="file">
when user selects a file(s) and then use Fetch to post the FileList wrapped around a FormData object.
// The input DOM element
const inputElement = document.querySelector('input');
// Listen for a file submit from user
inputElement.addEventListener('change', () => {
const data = new FormData();
data.append('file', inputElement.files[0]);
data.append('imageName', 'flower');
// Post to server
fetch('/uploadImage', {
method: 'POST',
body: data
});
});
add a comment |
up vote
7
down vote
up vote
7
down vote
A modern approach without Jquery is to use the FileList object you get back from <input type="file">
when user selects a file(s) and then use Fetch to post the FileList wrapped around a FormData object.
// The input DOM element
const inputElement = document.querySelector('input');
// Listen for a file submit from user
inputElement.addEventListener('change', () => {
const data = new FormData();
data.append('file', inputElement.files[0]);
data.append('imageName', 'flower');
// Post to server
fetch('/uploadImage', {
method: 'POST',
body: data
});
});
A modern approach without Jquery is to use the FileList object you get back from <input type="file">
when user selects a file(s) and then use Fetch to post the FileList wrapped around a FormData object.
// The input DOM element
const inputElement = document.querySelector('input');
// Listen for a file submit from user
inputElement.addEventListener('change', () => {
const data = new FormData();
data.append('file', inputElement.files[0]);
data.append('imageName', 'flower');
// Post to server
fetch('/uploadImage', {
method: 'POST',
body: data
});
});
edited Nov 20 at 12:49
answered Aug 17 at 11:47
Alister Norris
9,77332519
9,77332519
add a comment |
add a comment |
up vote
5
down vote
Look for Handling the upload process for a file, asynchronously in here:
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
Sample from the link
<?php
if (isset($_FILES['myFile'])) {
// Example:
move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']);
exit;
}
?><!DOCTYPE html>
<html>
<head>
<title>dnd binary upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function sendFile(file) {
var uri = "/index.php";
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", uri, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Handle response.
alert(xhr.responseText); // handle response.
}
};
fd.append('myFile', file);
// Initiate a multipart/form-data upload
xhr.send(fd);
}
window.onload = function() {
var dropzone = document.getElementById("dropzone");
dropzone.ondragover = dropzone.ondragenter = function(event) {
event.stopPropagation();
event.preventDefault();
}
dropzone.ondrop = function(event) {
event.stopPropagation();
event.preventDefault();
var filesArray = event.dataTransfer.files;
for (var i=0; i<filesArray.length; i++) {
sendFile(filesArray[i]);
}
}
}
</script>
</head>
<body>
<div>
<div id="dropzone" style="margin:30px; width:500px; height:300px; border:1px dotted grey;">Drag & drop your file here...</div>
</div>
</body>
</html>
add a comment |
up vote
5
down vote
Look for Handling the upload process for a file, asynchronously in here:
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
Sample from the link
<?php
if (isset($_FILES['myFile'])) {
// Example:
move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']);
exit;
}
?><!DOCTYPE html>
<html>
<head>
<title>dnd binary upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function sendFile(file) {
var uri = "/index.php";
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", uri, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Handle response.
alert(xhr.responseText); // handle response.
}
};
fd.append('myFile', file);
// Initiate a multipart/form-data upload
xhr.send(fd);
}
window.onload = function() {
var dropzone = document.getElementById("dropzone");
dropzone.ondragover = dropzone.ondragenter = function(event) {
event.stopPropagation();
event.preventDefault();
}
dropzone.ondrop = function(event) {
event.stopPropagation();
event.preventDefault();
var filesArray = event.dataTransfer.files;
for (var i=0; i<filesArray.length; i++) {
sendFile(filesArray[i]);
}
}
}
</script>
</head>
<body>
<div>
<div id="dropzone" style="margin:30px; width:500px; height:300px; border:1px dotted grey;">Drag & drop your file here...</div>
</div>
</body>
</html>
add a comment |
up vote
5
down vote
up vote
5
down vote
Look for Handling the upload process for a file, asynchronously in here:
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
Sample from the link
<?php
if (isset($_FILES['myFile'])) {
// Example:
move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']);
exit;
}
?><!DOCTYPE html>
<html>
<head>
<title>dnd binary upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function sendFile(file) {
var uri = "/index.php";
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", uri, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Handle response.
alert(xhr.responseText); // handle response.
}
};
fd.append('myFile', file);
// Initiate a multipart/form-data upload
xhr.send(fd);
}
window.onload = function() {
var dropzone = document.getElementById("dropzone");
dropzone.ondragover = dropzone.ondragenter = function(event) {
event.stopPropagation();
event.preventDefault();
}
dropzone.ondrop = function(event) {
event.stopPropagation();
event.preventDefault();
var filesArray = event.dataTransfer.files;
for (var i=0; i<filesArray.length; i++) {
sendFile(filesArray[i]);
}
}
}
</script>
</head>
<body>
<div>
<div id="dropzone" style="margin:30px; width:500px; height:300px; border:1px dotted grey;">Drag & drop your file here...</div>
</div>
</body>
</html>
Look for Handling the upload process for a file, asynchronously in here:
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
Sample from the link
<?php
if (isset($_FILES['myFile'])) {
// Example:
move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']);
exit;
}
?><!DOCTYPE html>
<html>
<head>
<title>dnd binary upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function sendFile(file) {
var uri = "/index.php";
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", uri, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// Handle response.
alert(xhr.responseText); // handle response.
}
};
fd.append('myFile', file);
// Initiate a multipart/form-data upload
xhr.send(fd);
}
window.onload = function() {
var dropzone = document.getElementById("dropzone");
dropzone.ondragover = dropzone.ondragenter = function(event) {
event.stopPropagation();
event.preventDefault();
}
dropzone.ondrop = function(event) {
event.stopPropagation();
event.preventDefault();
var filesArray = event.dataTransfer.files;
for (var i=0; i<filesArray.length; i++) {
sendFile(filesArray[i]);
}
}
}
</script>
</head>
<body>
<div>
<div id="dropzone" style="margin:30px; width:500px; height:300px; border:1px dotted grey;">Drag & drop your file here...</div>
</div>
</body>
</html>
edited Oct 31 '17 at 22:19
Mark Amery
59k30234282
59k30234282
answered Jul 8 '15 at 17:59
Allende
1,10021836
1,10021836
add a comment |
add a comment |
up vote
5
down vote
You can pass additional parameters along with file name on making asynchronous upload using XMLHttpRequest (without flash and iframe dependency). Append the additional parameter value with FormData and send the upload request.
var formData = new FormData();
formData.append('parameter1', 'value1');
formData.append('parameter2', 'value2');
formData.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'post back url',
data: formData,
// other attributes of AJAX
});
Also, Syncfusion JavaScript UI file upload provides solution for this scenario simply using event argument. you can find documentation here and further details about this control here enter link description here
add a comment |
up vote
5
down vote
You can pass additional parameters along with file name on making asynchronous upload using XMLHttpRequest (without flash and iframe dependency). Append the additional parameter value with FormData and send the upload request.
var formData = new FormData();
formData.append('parameter1', 'value1');
formData.append('parameter2', 'value2');
formData.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'post back url',
data: formData,
// other attributes of AJAX
});
Also, Syncfusion JavaScript UI file upload provides solution for this scenario simply using event argument. you can find documentation here and further details about this control here enter link description here
add a comment |
up vote
5
down vote
up vote
5
down vote
You can pass additional parameters along with file name on making asynchronous upload using XMLHttpRequest (without flash and iframe dependency). Append the additional parameter value with FormData and send the upload request.
var formData = new FormData();
formData.append('parameter1', 'value1');
formData.append('parameter2', 'value2');
formData.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'post back url',
data: formData,
// other attributes of AJAX
});
Also, Syncfusion JavaScript UI file upload provides solution for this scenario simply using event argument. you can find documentation here and further details about this control here enter link description here
You can pass additional parameters along with file name on making asynchronous upload using XMLHttpRequest (without flash and iframe dependency). Append the additional parameter value with FormData and send the upload request.
var formData = new FormData();
formData.append('parameter1', 'value1');
formData.append('parameter2', 'value2');
formData.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'post back url',
data: formData,
// other attributes of AJAX
});
Also, Syncfusion JavaScript UI file upload provides solution for this scenario simply using event argument. you can find documentation here and further details about this control here enter link description here
edited Nov 15 at 5:06
answered Nov 14 at 12:42
Karthik Ravichandran
316213
316213
add a comment |
add a comment |
up vote
4
down vote
This is my solution.
<form enctype="multipart/form-data">
<div class="form-group">
<label class="control-label col-md-2" for="apta_Description">Description</label>
<div class="col-md-10">
<input class="form-control text-box single-line" id="apta_Description" name="apta_Description" type="text" value="">
</div>
</div>
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
and the js
<script>
$(':button').click(function () {
var formData = new FormData($('form')[0]);
$.ajax({
url: '@Url.Action("Save", "Home")',
type: 'POST',
success: completeHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
});
function completeHandler() {
alert(":)");
}
</script>
Controller
[HttpPost]
public ActionResult Save(string apta_Description, HttpPostedFileBase file)
{
return Json(":)");
}
1
You seem to have mixed some kind of framework into your answer. You should, at the very least, mention which framework your answer is usable for. Better yet, remove all the framework stuff and present only an answer to the question posed.
– Zero3
Dec 19 '15 at 18:06
2
so there's actually a mvc framework called "mvc"? and it uses csharpish syntax? that's cruel.
– nonchip
Jan 6 '16 at 22:27
add a comment |
up vote
4
down vote
This is my solution.
<form enctype="multipart/form-data">
<div class="form-group">
<label class="control-label col-md-2" for="apta_Description">Description</label>
<div class="col-md-10">
<input class="form-control text-box single-line" id="apta_Description" name="apta_Description" type="text" value="">
</div>
</div>
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
and the js
<script>
$(':button').click(function () {
var formData = new FormData($('form')[0]);
$.ajax({
url: '@Url.Action("Save", "Home")',
type: 'POST',
success: completeHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
});
function completeHandler() {
alert(":)");
}
</script>
Controller
[HttpPost]
public ActionResult Save(string apta_Description, HttpPostedFileBase file)
{
return Json(":)");
}
1
You seem to have mixed some kind of framework into your answer. You should, at the very least, mention which framework your answer is usable for. Better yet, remove all the framework stuff and present only an answer to the question posed.
– Zero3
Dec 19 '15 at 18:06
2
so there's actually a mvc framework called "mvc"? and it uses csharpish syntax? that's cruel.
– nonchip
Jan 6 '16 at 22:27
add a comment |
up vote
4
down vote
up vote
4
down vote
This is my solution.
<form enctype="multipart/form-data">
<div class="form-group">
<label class="control-label col-md-2" for="apta_Description">Description</label>
<div class="col-md-10">
<input class="form-control text-box single-line" id="apta_Description" name="apta_Description" type="text" value="">
</div>
</div>
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
and the js
<script>
$(':button').click(function () {
var formData = new FormData($('form')[0]);
$.ajax({
url: '@Url.Action("Save", "Home")',
type: 'POST',
success: completeHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
});
function completeHandler() {
alert(":)");
}
</script>
Controller
[HttpPost]
public ActionResult Save(string apta_Description, HttpPostedFileBase file)
{
return Json(":)");
}
This is my solution.
<form enctype="multipart/form-data">
<div class="form-group">
<label class="control-label col-md-2" for="apta_Description">Description</label>
<div class="col-md-10">
<input class="form-control text-box single-line" id="apta_Description" name="apta_Description" type="text" value="">
</div>
</div>
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
and the js
<script>
$(':button').click(function () {
var formData = new FormData($('form')[0]);
$.ajax({
url: '@Url.Action("Save", "Home")',
type: 'POST',
success: completeHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
});
function completeHandler() {
alert(":)");
}
</script>
Controller
[HttpPost]
public ActionResult Save(string apta_Description, HttpPostedFileBase file)
{
return Json(":)");
}
edited Apr 10 at 15:07
answered Nov 3 '15 at 20:47
Erick Langford Xenes
8511821
8511821
1
You seem to have mixed some kind of framework into your answer. You should, at the very least, mention which framework your answer is usable for. Better yet, remove all the framework stuff and present only an answer to the question posed.
– Zero3
Dec 19 '15 at 18:06
2
so there's actually a mvc framework called "mvc"? and it uses csharpish syntax? that's cruel.
– nonchip
Jan 6 '16 at 22:27
add a comment |
1
You seem to have mixed some kind of framework into your answer. You should, at the very least, mention which framework your answer is usable for. Better yet, remove all the framework stuff and present only an answer to the question posed.
– Zero3
Dec 19 '15 at 18:06
2
so there's actually a mvc framework called "mvc"? and it uses csharpish syntax? that's cruel.
– nonchip
Jan 6 '16 at 22:27
1
1
You seem to have mixed some kind of framework into your answer. You should, at the very least, mention which framework your answer is usable for. Better yet, remove all the framework stuff and present only an answer to the question posed.
– Zero3
Dec 19 '15 at 18:06
You seem to have mixed some kind of framework into your answer. You should, at the very least, mention which framework your answer is usable for. Better yet, remove all the framework stuff and present only an answer to the question posed.
– Zero3
Dec 19 '15 at 18:06
2
2
so there's actually a mvc framework called "mvc"? and it uses csharpish syntax? that's cruel.
– nonchip
Jan 6 '16 at 22:27
so there's actually a mvc framework called "mvc"? and it uses csharpish syntax? that's cruel.
– nonchip
Jan 6 '16 at 22:27
add a comment |
up vote
3
down vote
Using HTML5 and JavaScript, uploading async is quite easy, I create the uploading logic along with your html, this is not fully working as it needs the api, but demonstrate how it works, if you have the endpoint called /upload
from root of your website, this code should work for you:
const asyncFileUpload = () => {
const fileInput = document.getElementById("file");
const file = fileInput.files[0];
const uri = "/upload";
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = e => {
const percentage = e.loaded / e.total;
console.log(percentage);
};
xhr.onreadystatechange = e => {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("file uploaded");
}
};
xhr.open("POST", uri, true);
xhr.setRequestHeader("X-FileName", file.name);
xhr.send(file);
}
<form>
<span>File</span>
<input type="file" id="file" name="file" size="10" />
<input onclick="asyncFileUpload()" id="upload" type="button" value="Upload" />
</form>
Also some further information about XMLHttpReques:
The XMLHttpRequest Object
All modern browsers support the XMLHttpRequest object.
The XMLHttpRequest object can be used to exchange data with a web
server behind the scenes. This means that it is possible to update
parts of a web page, without reloading the whole page.
Create an XMLHttpRequest Object
All modern browsers (Chrome, Firefox,
IE7+, Edge, Safari, Opera) have a built-in XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
variable = new XMLHttpRequest();
Access Across Domains
For security reasons, modern browsers do not
allow access across domains.
This means that both the web page and the XML file it tries to load,
must be located on the same server.
The examples on W3Schools all open XML files located on the W3Schools
domain.
If you want to use the example above on one of your own web pages, the
XML files you load must be located on your own server.
For more details, you can continue reading here...
add a comment |
up vote
3
down vote
Using HTML5 and JavaScript, uploading async is quite easy, I create the uploading logic along with your html, this is not fully working as it needs the api, but demonstrate how it works, if you have the endpoint called /upload
from root of your website, this code should work for you:
const asyncFileUpload = () => {
const fileInput = document.getElementById("file");
const file = fileInput.files[0];
const uri = "/upload";
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = e => {
const percentage = e.loaded / e.total;
console.log(percentage);
};
xhr.onreadystatechange = e => {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("file uploaded");
}
};
xhr.open("POST", uri, true);
xhr.setRequestHeader("X-FileName", file.name);
xhr.send(file);
}
<form>
<span>File</span>
<input type="file" id="file" name="file" size="10" />
<input onclick="asyncFileUpload()" id="upload" type="button" value="Upload" />
</form>
Also some further information about XMLHttpReques:
The XMLHttpRequest Object
All modern browsers support the XMLHttpRequest object.
The XMLHttpRequest object can be used to exchange data with a web
server behind the scenes. This means that it is possible to update
parts of a web page, without reloading the whole page.
Create an XMLHttpRequest Object
All modern browsers (Chrome, Firefox,
IE7+, Edge, Safari, Opera) have a built-in XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
variable = new XMLHttpRequest();
Access Across Domains
For security reasons, modern browsers do not
allow access across domains.
This means that both the web page and the XML file it tries to load,
must be located on the same server.
The examples on W3Schools all open XML files located on the W3Schools
domain.
If you want to use the example above on one of your own web pages, the
XML files you load must be located on your own server.
For more details, you can continue reading here...
add a comment |
up vote
3
down vote
up vote
3
down vote
Using HTML5 and JavaScript, uploading async is quite easy, I create the uploading logic along with your html, this is not fully working as it needs the api, but demonstrate how it works, if you have the endpoint called /upload
from root of your website, this code should work for you:
const asyncFileUpload = () => {
const fileInput = document.getElementById("file");
const file = fileInput.files[0];
const uri = "/upload";
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = e => {
const percentage = e.loaded / e.total;
console.log(percentage);
};
xhr.onreadystatechange = e => {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("file uploaded");
}
};
xhr.open("POST", uri, true);
xhr.setRequestHeader("X-FileName", file.name);
xhr.send(file);
}
<form>
<span>File</span>
<input type="file" id="file" name="file" size="10" />
<input onclick="asyncFileUpload()" id="upload" type="button" value="Upload" />
</form>
Also some further information about XMLHttpReques:
The XMLHttpRequest Object
All modern browsers support the XMLHttpRequest object.
The XMLHttpRequest object can be used to exchange data with a web
server behind the scenes. This means that it is possible to update
parts of a web page, without reloading the whole page.
Create an XMLHttpRequest Object
All modern browsers (Chrome, Firefox,
IE7+, Edge, Safari, Opera) have a built-in XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
variable = new XMLHttpRequest();
Access Across Domains
For security reasons, modern browsers do not
allow access across domains.
This means that both the web page and the XML file it tries to load,
must be located on the same server.
The examples on W3Schools all open XML files located on the W3Schools
domain.
If you want to use the example above on one of your own web pages, the
XML files you load must be located on your own server.
For more details, you can continue reading here...
Using HTML5 and JavaScript, uploading async is quite easy, I create the uploading logic along with your html, this is not fully working as it needs the api, but demonstrate how it works, if you have the endpoint called /upload
from root of your website, this code should work for you:
const asyncFileUpload = () => {
const fileInput = document.getElementById("file");
const file = fileInput.files[0];
const uri = "/upload";
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = e => {
const percentage = e.loaded / e.total;
console.log(percentage);
};
xhr.onreadystatechange = e => {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("file uploaded");
}
};
xhr.open("POST", uri, true);
xhr.setRequestHeader("X-FileName", file.name);
xhr.send(file);
}
<form>
<span>File</span>
<input type="file" id="file" name="file" size="10" />
<input onclick="asyncFileUpload()" id="upload" type="button" value="Upload" />
</form>
Also some further information about XMLHttpReques:
The XMLHttpRequest Object
All modern browsers support the XMLHttpRequest object.
The XMLHttpRequest object can be used to exchange data with a web
server behind the scenes. This means that it is possible to update
parts of a web page, without reloading the whole page.
Create an XMLHttpRequest Object
All modern browsers (Chrome, Firefox,
IE7+, Edge, Safari, Opera) have a built-in XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:
variable = new XMLHttpRequest();
Access Across Domains
For security reasons, modern browsers do not
allow access across domains.
This means that both the web page and the XML file it tries to load,
must be located on the same server.
The examples on W3Schools all open XML files located on the W3Schools
domain.
If you want to use the example above on one of your own web pages, the
XML files you load must be located on your own server.
For more details, you can continue reading here...
const asyncFileUpload = () => {
const fileInput = document.getElementById("file");
const file = fileInput.files[0];
const uri = "/upload";
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = e => {
const percentage = e.loaded / e.total;
console.log(percentage);
};
xhr.onreadystatechange = e => {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("file uploaded");
}
};
xhr.open("POST", uri, true);
xhr.setRequestHeader("X-FileName", file.name);
xhr.send(file);
}
<form>
<span>File</span>
<input type="file" id="file" name="file" size="10" />
<input onclick="asyncFileUpload()" id="upload" type="button" value="Upload" />
</form>
const asyncFileUpload = () => {
const fileInput = document.getElementById("file");
const file = fileInput.files[0];
const uri = "/upload";
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = e => {
const percentage = e.loaded / e.total;
console.log(percentage);
};
xhr.onreadystatechange = e => {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("file uploaded");
}
};
xhr.open("POST", uri, true);
xhr.setRequestHeader("X-FileName", file.name);
xhr.send(file);
}
<form>
<span>File</span>
<input type="file" id="file" name="file" size="10" />
<input onclick="asyncFileUpload()" id="upload" type="button" value="Upload" />
</form>
edited Jul 18 at 11:09
answered Mar 12 at 12:32
Alireza
43.8k12161118
43.8k12161118
add a comment |
add a comment |
up vote
2
down vote
You can use newer Fetch API by JavaScript. Like this:
function uploadButtonCLicked(){
var input = document.querySelector('input[type="file"]')
fetch('/url', {
method: 'POST',
body: input.files[0]
}).then(res => res.json()) // you can do something with response
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
Advantage: Fetch API is natively supported by all modern browsers, so you don't have to import anything. Also, note that fetch() returns a Promise which is then handled by using .then(..code to handle response..)
asynchronously.
add a comment |
up vote
2
down vote
You can use newer Fetch API by JavaScript. Like this:
function uploadButtonCLicked(){
var input = document.querySelector('input[type="file"]')
fetch('/url', {
method: 'POST',
body: input.files[0]
}).then(res => res.json()) // you can do something with response
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
Advantage: Fetch API is natively supported by all modern browsers, so you don't have to import anything. Also, note that fetch() returns a Promise which is then handled by using .then(..code to handle response..)
asynchronously.
add a comment |
up vote
2
down vote
up vote
2
down vote
You can use newer Fetch API by JavaScript. Like this:
function uploadButtonCLicked(){
var input = document.querySelector('input[type="file"]')
fetch('/url', {
method: 'POST',
body: input.files[0]
}).then(res => res.json()) // you can do something with response
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
Advantage: Fetch API is natively supported by all modern browsers, so you don't have to import anything. Also, note that fetch() returns a Promise which is then handled by using .then(..code to handle response..)
asynchronously.
You can use newer Fetch API by JavaScript. Like this:
function uploadButtonCLicked(){
var input = document.querySelector('input[type="file"]')
fetch('/url', {
method: 'POST',
body: input.files[0]
}).then(res => res.json()) // you can do something with response
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
Advantage: Fetch API is natively supported by all modern browsers, so you don't have to import anything. Also, note that fetch() returns a Promise which is then handled by using .then(..code to handle response..)
asynchronously.
edited May 22 at 16:05
answered May 21 at 10:14
BlackBeard
4,71442036
4,71442036
add a comment |
add a comment |
up vote
2
down vote
You can do the Asynchronous Multiple File uploads using JavaScript or jQuery and that to without using any plugin. You can also show the real time progress of file upload in the progress control. I have come across 2 nice links -
- ASP.NET Web Forms based Mulitple File Upload Feature with Progress Bar
- ASP.NET MVC based Multiple File Upload made in jQuery
The server side language is C# but you can do some modification for making it work with other language like PHP.
File Upload ASP.NET Core MVC:
In the View create file upload control in html:
<form method="post" asp-action="Add" enctype="multipart/form-data">
<input type="file" multiple name="mediaUpload" />
<button type="submit">Submit</button>
</form>
Now create action method in your controller:
[HttpPost]
public async Task<IActionResult> Add(IFormFile mediaUpload)
{
//looping through all the files
foreach (IFormFile file in mediaUpload)
{
//saving the files
string path = Path.Combine(hostingEnvironment.WebRootPath, "some-folder-path");
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
}
hostingEnvironment variable is of type IHostingEnvironment which can be injected to the controller using dependency injection, like:
private IHostingEnvironment hostingEnvironment;
public MediaController(IHostingEnvironment environment)
{
hostingEnvironment = environment;
}
Could you include the essence of the solution in your answer, as it otherwise might become useless if the linked website changes or goes offline.
– Dima Kozhevin
Aug 29 at 20:12
add a comment |
up vote
2
down vote
You can do the Asynchronous Multiple File uploads using JavaScript or jQuery and that to without using any plugin. You can also show the real time progress of file upload in the progress control. I have come across 2 nice links -
- ASP.NET Web Forms based Mulitple File Upload Feature with Progress Bar
- ASP.NET MVC based Multiple File Upload made in jQuery
The server side language is C# but you can do some modification for making it work with other language like PHP.
File Upload ASP.NET Core MVC:
In the View create file upload control in html:
<form method="post" asp-action="Add" enctype="multipart/form-data">
<input type="file" multiple name="mediaUpload" />
<button type="submit">Submit</button>
</form>
Now create action method in your controller:
[HttpPost]
public async Task<IActionResult> Add(IFormFile mediaUpload)
{
//looping through all the files
foreach (IFormFile file in mediaUpload)
{
//saving the files
string path = Path.Combine(hostingEnvironment.WebRootPath, "some-folder-path");
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
}
hostingEnvironment variable is of type IHostingEnvironment which can be injected to the controller using dependency injection, like:
private IHostingEnvironment hostingEnvironment;
public MediaController(IHostingEnvironment environment)
{
hostingEnvironment = environment;
}
Could you include the essence of the solution in your answer, as it otherwise might become useless if the linked website changes or goes offline.
– Dima Kozhevin
Aug 29 at 20:12
add a comment |
up vote
2
down vote
up vote
2
down vote
You can do the Asynchronous Multiple File uploads using JavaScript or jQuery and that to without using any plugin. You can also show the real time progress of file upload in the progress control. I have come across 2 nice links -
- ASP.NET Web Forms based Mulitple File Upload Feature with Progress Bar
- ASP.NET MVC based Multiple File Upload made in jQuery
The server side language is C# but you can do some modification for making it work with other language like PHP.
File Upload ASP.NET Core MVC:
In the View create file upload control in html:
<form method="post" asp-action="Add" enctype="multipart/form-data">
<input type="file" multiple name="mediaUpload" />
<button type="submit">Submit</button>
</form>
Now create action method in your controller:
[HttpPost]
public async Task<IActionResult> Add(IFormFile mediaUpload)
{
//looping through all the files
foreach (IFormFile file in mediaUpload)
{
//saving the files
string path = Path.Combine(hostingEnvironment.WebRootPath, "some-folder-path");
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
}
hostingEnvironment variable is of type IHostingEnvironment which can be injected to the controller using dependency injection, like:
private IHostingEnvironment hostingEnvironment;
public MediaController(IHostingEnvironment environment)
{
hostingEnvironment = environment;
}
You can do the Asynchronous Multiple File uploads using JavaScript or jQuery and that to without using any plugin. You can also show the real time progress of file upload in the progress control. I have come across 2 nice links -
- ASP.NET Web Forms based Mulitple File Upload Feature with Progress Bar
- ASP.NET MVC based Multiple File Upload made in jQuery
The server side language is C# but you can do some modification for making it work with other language like PHP.
File Upload ASP.NET Core MVC:
In the View create file upload control in html:
<form method="post" asp-action="Add" enctype="multipart/form-data">
<input type="file" multiple name="mediaUpload" />
<button type="submit">Submit</button>
</form>
Now create action method in your controller:
[HttpPost]
public async Task<IActionResult> Add(IFormFile mediaUpload)
{
//looping through all the files
foreach (IFormFile file in mediaUpload)
{
//saving the files
string path = Path.Combine(hostingEnvironment.WebRootPath, "some-folder-path");
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
}
hostingEnvironment variable is of type IHostingEnvironment which can be injected to the controller using dependency injection, like:
private IHostingEnvironment hostingEnvironment;
public MediaController(IHostingEnvironment environment)
{
hostingEnvironment = environment;
}
edited Sep 8 at 13:01
answered Aug 29 at 19:51
Joe Clinton
648
648
Could you include the essence of the solution in your answer, as it otherwise might become useless if the linked website changes or goes offline.
– Dima Kozhevin
Aug 29 at 20:12
add a comment |
Could you include the essence of the solution in your answer, as it otherwise might become useless if the linked website changes or goes offline.
– Dima Kozhevin
Aug 29 at 20:12
Could you include the essence of the solution in your answer, as it otherwise might become useless if the linked website changes or goes offline.
– Dima Kozhevin
Aug 29 at 20:12
Could you include the essence of the solution in your answer, as it otherwise might become useless if the linked website changes or goes offline.
– Dima Kozhevin
Aug 29 at 20:12
add a comment |
1 2
next
protected by Will Aug 30 '10 at 11:41
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
70
you are only getting the file name because your var filename is getting the value of $('#file'), not the file that lies in the input
– Jimmy
Nov 3 '09 at 16:01
21
Here's a good one: http://blueimp.github.io/jQuery-File-Upload/ - HTML5 ajax uploading - Graceful fallback to iframes for unsupported browsers - Multi-file async upload We've used it and it works great. (Documentation here)
– Ashish Panery
Apr 12 '13 at 18:35
jQuery Form Plugin seems the most simple-to-use and cross-browser compatible way... am I right ?
– Lyth
Sep 18 '13 at 12:32
3
Check also this: stackoverflow.com/questions/6974684/…, here it explains how to achieve it via jQuery
– Chococroc
Jan 15 '14 at 12:09
2
@Jimmy How would he get the get the file that lies in the input instead?
– alex
Dec 5 '14 at 18:05