我想用jQuery异步上传文件。

$(文档).ready(函数(){$(“#uploadbutton”).click(函数(){var filename=$(“#file”).val();$.ajax美元({类型:“POST”,url:“addFile.do”,enctype:'多部分/表单数据',数据:{文件:文件名},成功:函数(){alert(“上传的数据:”);}});});});<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js“></script><span>文件</span><input type=“file”id=“file”name=“file”size=“10”/><input id=“uploadbutton”type=“button”value=“Upload”/>

我只得到文件名,而不是上传文件。我可以做什么来解决这个问题?


当前回答

如果使用承诺使用哪种ajax,并检查文件是否有效并保存在后端,那么您可以在用户浏览页面时在前面使用一些动画。

您甚至可以使用递归方法使其并行上传或堆叠

其他回答

您可以使用JavaScript或jQuery进行异步多文件上传,而无需使用任何插件。您还可以在进度控件中显示文件上载的实时进度。我遇到了两个不错的链接-

带有进度条的基于ASP.NET Web表单的多文件上载功能jQuery中基于ASP.NET MVC的多文件上载

服务器端语言是C#,但您可以进行一些修改,使其与其他语言(如PHP)一起使用。

文件上载ASP.NET核心MVC:

在html中的View create file upload控件中:

<form method="post" asp-action="Add" enctype="multipart/form-data">
    <input type="file" multiple name="mediaUpload" />
    <button type="submit">Submit</button>
</form>

现在在控制器中创建动作方法:

[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变量的类型为IHostingEnvironment,可以使用依赖注入将其注入控制器,例如:

private IHostingEnvironment hostingEnvironment;
public MediaController(IHostingEnvironment environment)
{
    hostingEnvironment = environment;
}

注意:此答案已过时,现在可以使用XHR上载文件。


不能使用XMLHttpRequest(Ajax)上载文件。可以使用iframe或Flash模拟效果。优秀的jQuery表单插件,通过iframe发布文件以获得效果。

你也可以考虑使用类似的https://uppy.io.

它可以在不离开页面的情况下进行文件上传,并提供一些奖励,如拖放、在浏览器崩溃/网络不稳定的情况下恢复上传,以及从例如Instagram导入。它是开源的,不依赖于jQuery/React/Angular/Vue,但可以与它一起使用。免责声明:作为它的创建者,我有偏见;)

这是一个老问题,但仍然没有正确答案,因此:

您尝试过jQuery文件上载吗?

下面是上面链接中的一个示例,可以解决您的问题:

$('#fileupload').fileupload({
    add: function (e, data) {
        var that = this;
        $.getJSON('/example/url', function (result) {
            data.formData = result; // e.g. {id: 123}
            $.blueimp.fileupload.prototype
                .options.add.call(that, e, data);
        });
    } 
});

为未来读者整理。

异步文件上载

使用HTML5

如果支持FormData和File API(这两个HTML5功能),则可以使用$.ajax()方法使用jQuery上载文件。

您也可以在不使用FormData的情况下发送文件,但无论哪种方式,文件API都必须以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!");
});

有关快速纯JavaScript(无jQuery)示例,请参阅“使用FormData对象发送文件”。

退路

当HTML5不受支持(没有文件API)时,唯一的其他纯JavaScript解决方案(没有Flash或任何其他浏览器插件)是隐藏的iframe技术,它允许在不使用XMLHttpRequest对象的情况下模拟异步请求。

它包括使用文件输入将iframe设置为表单的目标。当用户提交请求并上传文件时,响应显示在iframe中,而不是重新呈现主页。隐藏iframe使整个过程对用户透明,并模拟异步请求。

如果处理得当,它实际上应该可以在任何浏览器上运行,但它对如何从iframe中获取响应有一些警告。

在这种情况下,您可能更喜欢使用像Bifröst这样的包装器插件,它使用iframe技术,但也提供jQueryAjax传输,允许仅使用$.Ajax()方法发送文件,如下所示:

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

插件

Bifröst只是一个小包装,它为jQuery的ajax方法添加了回退支持,但前面提到的许多插件,如jQuery表单插件或jQuery文件上载,都包括从HTML5到不同回退的整个堆栈,以及一些有用的功能来简化过程。根据您的需要和要求,您可能需要考虑一个简单的实现或其中一个插件。