简体   繁体   English

异步JQUERY文件上传

[英]Asynchronous JQUERY File Upload

I have HTML form with a file input type. 我有带有文件输入类型的HTML表单。 I need to submit the form asynchronously to the server. 我需要将表单异步提交到服务器。 The server listens for a incoming file upload (multi part file upload) request. 服务器侦听传入的文件上载(多部分文件上载)请求。 Is it possible to achieve this using jquery. 是否有可能使用jquery来实现。

You can easily use jQuery's $.ajax() method to send files if FormData and the File API are supported (both HTML5 features). 如果支持FormDataFile API (均具有HTML5功能),则可以轻松使用jQuery的$.ajax()方法发送文件。

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). 您也可以发送不带FormData的文件但是必须以两种方式发送文件API来处理文件,以便可以使用XMLHttpRequest(Ajax)发送文件。

$.ajax({
  url: 'file/destination.html', 
  type: 'POST',
  data: new FormData($('#formWithFiles')[0]),  // The form with the file inputs.
  processData: false  // Using FormData, don't 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 example see " Sending files using a FormData object ". 有关快速的纯JavaScript示例,请参见“ 使用FormData对象发送文件 ”。

If you want to add a fallback for older browsers or if you want just one cross-browser implementation use the Bifröst . 如果您想为旧版浏览器添加一个后备版本,或者只想使用一个跨浏览器实现,请使用Bifröst It adds an extra jQuery Ajax transport allowing to send files with plane old $.ajax() . 它增加了一个额外的jQuery Ajax传输,允许使用旧的$.ajax()发送文件

Simply add jquery.bifrost.js and make the request: 只需添加jquery.bifrost.js并发出请求:

$.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!");
});

Good luck! 祝好运!

Is it possible to achieve this using jquery. 是否有可能使用jquery来实现。

No, not directly with jQuery. 不,不是直接使用jQuery。

You could use the HTML5 File API: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications 您可以使用HTML5文件API: https : //developer.mozilla.org/en-US/docs/Using_files_from_web_applications

Or if you need to support legacy browsers you could use some plugin such as Uploadify , Fine Uploader or the jQuery form plugin . 或者,如果您需要支持旧版浏览器,则可以使用某些插件,例如UploadifyFine UploaderjQuery form plugin

I would take a look at this jQuery plugin: 我来看看这个jQuery插件:

http://malsup.com/jquery/form/#file-upload http://malsup.com/jquery/form/#file-upload

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM