异步JQUERY文件上传 [英] Asynchronous JQUERY File Upload

查看:151
本文介绍了异步JQUERY文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件输入类型的HTML表单。我需要将表单异步提交给服务器。服务器侦听传入文件上传(多部分文件上传)请求。是否有可能实现这个使用jQuery。

解决方案

您可以轻松使用jQuery的 $。ajax()如果 FormData File API (都是HTML5功能)。

您也可以发送文件,但是无论如何,File API必须存在才能以XMLHttpRequest(Ajax)方式处理文件。

  $。ajax({
url:'file / destination.html',
type:'POST',
data:new FormData($('#formWithFiles')[0]),//带有文件输入的表单
processData:false //使用FormData,不处理数据
})。done函数(){
console.log(Success:Files sent!);
})。fail(function(){
console.log(发生错误,文件couldn 't be sent!);
});

有关快速,纯粹的JavaScript示例,请参阅使用FormData对象发送文件

如果您想为旧浏览器添加后备,或者只需要一个跨浏览器实施,请使用Bifröst。它增加了一个额外的 jQuery Ajax传输,允许用旧的<$ $平面发送文件 c $ c $ $ ajax()。



只需添加 jquery.bifrost.js

  $。ajax({
url:'file / destination.html',
type: 'POST',
//设置要使用的传输(iframe意味着使用Bifröst)
//以及期望的数据类型(本例中为json)
dataType:'iframe json' ,
fileInputs:$('input [type =file]'),//包含要发送文件的文件输入
data:{msg:'你可能需要一些额外的数据。 ();
})。done(function(){
console.log(Success:Files sent!);
})。日志(发生错误,文件无法发送!);
});

祝您好运!


I have HTML form with a file input type. 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.

解决方案

You can easily use jQuery's $.ajax() method to send files 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  // 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".

If you want to add a fallback for older browsers or if you want just one cross-browser implementation use the Bifröst. It adds an extra jQuery Ajax transport allowing to send files with plane old $.ajax().

Simply add jquery.bifrost.js and make the request:

$.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!

这篇关于异步JQUERY文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆