最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Input File upload success? - Stack Overflow

programmeradmin1浏览0评论

I have a quite plex form that has one "file" input, such as:

<input type="file" />

Is it possible to trigger some kind of "upload successful" with JS, so after user uploads the file the whole form submits itself?

I have a quite plex form that has one "file" input, such as:

<input type="file" />

Is it possible to trigger some kind of "upload successful" with JS, so after user uploads the file the whole form submits itself?

Share Improve this question asked Feb 11, 2014 at 9:38 user3245449user3245449 431 silver badge3 bronze badges 5
  • What do you mean by "user uploads the file the whole form submits itself?"? – Rahil Wazir Commented Feb 11, 2014 at 9:41
  • On a syncronous upload, the file will be uploaded on the actual submit event. Look in to XmlHttpRequest2 – Johan Commented Feb 11, 2014 at 9:41
  • Okay, so I have a plex form and user can fill the whole form OR upload a file (which is then processed in the back). Right now user is able to fill the form, then eventually upload the file then he has to click "Submit" to send the form. I want the form to be submitted automatically just after user uploads the file. – user3245449 Commented Feb 11, 2014 at 9:42
  • Listen for the file input fields change event and trigger the submit programatically. – Johan Commented Feb 11, 2014 at 9:44
  • Can you paste the jquery ajax code which you use for upoading the file . then it would be more easy for us to analyse and suggest you a work around. – Philemon philip Kunjumon Commented Feb 11, 2014 at 9:47
Add a ment  | 

2 Answers 2

Reset to default 5

You can upload your files asynchronously (if you want you may upload multiple files). So for example:

<input type="file" class="js-file-upload" multiple>

After creating input tag, you can listen to change event

$(".js-file-upload").on("change", function(e){
 var files = e.target.files;
 // your own logic to filter files etc.
 // upload your file
});

After all this you can listen to upload finish event (to submit after loading all files for example). Javascript XMLHttpRequest object provides two events: upload.progress and load. So use it ))

Pseudocode from my project:

file.on("upload.progress", function(e){
  //value show progress
  var value = Math.floor(e.loaded / e.total * 100);
});
file.on("load", function(response){ //logic });

I would remend jQuery File Upload for this purpose. The done callback informs the client that the file was uploaded successfully. Then you would be able to submit the corresponding form. There are many more useful callbacks (e.g. a failure callback).

发布评论

评论列表(0)

  1. 暂无评论