异步JQUERY文件上载
我有一个带有文件输入类型的HTML表单。 我需要将表单异步提交给服务器。 服务器侦听传入文件上载(多部分文件上载)请求。 是否有可能使用jquery实现这一点。
如果支持FormData和File API (HTML5function),您可以轻松使用jQuery的$.ajax()
方法发送文件。
您也可以在没有FormData的情况下发送文件,但无论是哪种方式,都必须存在File 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!"); });
有关快速纯JavaScript的示例,请参阅“ 使用FormData对象发送文件 ”。
如果您想为旧浏览器添加备用 ,或者如果您只想要一个跨浏览器实现,请使用Bifröst 。 它增加了一个额外的jQuery Ajax传输,允许发送带有旧的$.ajax()
。
只需添加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!"); });
祝好运!
是否有可能使用jquery实现这一点。
不,不是直接使用jQuery。
您可以使用HTML5文件API: https : //developer.mozilla.org/en-US/docs/Using_files_from_web_applications
或者,如果您需要支持旧版浏览器,您可以使用一些插件,如Uploadify
, Fine Uploader
或jQuery form plugin
。
我会看一下这个jQuery插件: