使用XmlHttpRequest进行Web API异步上载以获取进度



我正在尝试用进度条拖放文件上传。

我有一个div,它正在监听被丢弃的文件,它运行得很好。那我。。

//Setting up a XmlHttpRequest 
xhr = new XMLHttpRequest();
//Open connection
xhr.open("post", "api/ImageUpload", true);
// Set appropriate headers
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Type", uf.type);
xhr.setRequestHeader("X-File-Name", uf.name);
xhr.setRequestHeader("X-File-Size", uf.size);

这发送得很好,将流作为到Web API的请求的主体(不是异步的)。

[System.Web.Mvc.HttpPost]
public string Post()
{
    Stream stream =  HttpContext.Current.Request.InputStream;
    String filename = HttpContext.Current.Request.Headers["X-File-Name"];
    FileModel file = uploadService.UploadFile(stream, filename);
    return file.Id.ToString();
 }

我正在尝试将请求发送到"public async Task<string>Post(){}

如果该方法在页面上使用多部分表单而不是XmlHttpRequest,我会使用"wait Request.Content.ReadAsMultipartAsync(provider)",但在我需要它时似乎没有填充。

那么,正确的方法是处理Web API上的XmlHttpRequest和Async调用,以便用XHR的进度事件记录请求过程中的进度?

到目前为止,我已经看了很多页面来寻找解决方案,但这是我主要使用的页面。http://robertnyman.com/html5/fileapi-upload/fileapi-upload.html

谢谢你的帮助Oliver

看起来其他人也和你有同样的问题,但还没有得到答案。请看一下ASP.NET MVC 4 Web Api ajax文件上传。下面是微软的一个例子http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-第2部分

我把上面的两个解决方案结合在一起,为我工作(只是稍微调整一下)

  1. Javascritp 中的一行更改

    xhr.open("post","api/upload",true);

  2. 使用流保存文件

public class UploadController : ApiController
{
    public async Task<HttpResponseMessage> PostFormData()
    {
        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var fileName = Path.Combine(root, Request.Headers.GetValues("X-File-Name").First());
        try
        {
            var writer = new StreamWriter(fileName);
            await Request.Content.CopyToAsync(writer.BaseStream);
            writer.Close();
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }
}

最新更新