AJAX:将文件异步发布到服务器

AJAX: Asynchronously posting a file to a server

本文关键字:服务器 异步 文件 AJAX      更新时间:2023-09-26

我想在不发布表单的情况下异步将文件发布到服务器。我有以下代码:

var fileInput = document.getElementById('FileInput');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file, file.name);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://servername/controllername/AnalyseFile', true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
xhr.send(formData);

但是,在服务器上执行该方法时,帖子正文不包含任何文件。以下内容来自 ASP.NET MVC4:

[HttpPost]
public JsonResult AnalyseFile()
{
  int filesCount = Request.Files.Count;
  if(filesCount == 0) { throw new Exception('no files...'); }
  // do stuff
}
文件

集合不包含任何文件,我不知道为什么。任何帮助表示赞赏。

在视图中,您可以执行以下操作:

<form>
<input name="input1" id="input1"/>
<input name="input2" id="input2"/>
<input name="input3" id="input3"/>
...
<input id="SelectedFile" name="SelectedFile" type="file"/>
</form>

和Javascript:

function AttLogic(_url, _data, _callback) {
    $.ajax({
        url: _url,
        type: 'POST',
        xhr: function () {
            var myXhr = $.ajaxSettings.xhr();
            if (myXhr.upload) { }
            return myXhr;
        },
        data: _data,
        cache: !1,
        success: _callback,
        contentType: !1,
        processData: !1
    });
}
function FormDataCustom(f) {
    var __frm = jQuery(f), data = new FormData(f);
    $(':disabled[name]', __frm).each(function () {
        data.append(this.name, $(this).val());
    });
    return data;
}
function SaveLogic(){
var dt = FormDataCustom(document.forms[0]);
AttLogic(yourUrl, dt, function (r) {
        //do something here
    });
}

在控制器中:

public ActionResult Save(parameter1,parameter1,..., List<HttpPostedFileBase> SelectedFile)
{
    //do something here
}

您需要从请求中读取 MultiPartFormData。

根据这篇文章:

您的方法将如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Some.Namespace
{
    public class SomeController : ApiController
    {
        [HttpPost]
        public async Task<JsonResult> AnalyseFile()
        {
             if (!Request.Content.IsMimeMultipartContent())
             {
                 //If not throw an error
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
             }
             MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider("c:''tmp''uploads");
            // Read the MIME multipart content using the stream provider we just created.
            IEnumerable<HttpContent> bodyparts = await  Request.Content.ReadAsMultipartAsync(streamProvider);
            // Get a dictionary of local file names from stream provider.
            // The filename parameters provided in Content-Disposition header fields are the keys.
            // The local file names where the files are stored are the values.
            //depending on your version of .net, this might have been changed to FileData instead. 
            // see: https://msdn.microsoft.com/en-us/library/system.net.http.multipartformdatastreamprovider(v=vs.118).aspx
            IDictionary<string, string> bodyPartFileNames = streamProvider.BodyPartFileNames;
            //rest of code here
    }
}

我还没有测试上面的代码,但它应该为你指明正确的方向。

另请查看如何接受文件 POST

有关最近的文章: https://code.msdn.microsoft.com/AngularJS-with-Web-API-22f62a6e