【问题标题】:Web API Async Upload with XmlHttpRequest to get progress使用 XmlHttpRequest 进行 Web API 异步上传以获取进度
【发布时间】:2013-12-12 11:13:20
【问题描述】:

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

我有一个 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 Post(){ }

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

那么正确的做法是在 Web API 上处理来自 XmlHttpRequest 的异步调用,以便使用 XHR 的进度事件记录请求期间的进度?

到目前为止,我查看了大量页面以找到解决方案,但这是我主要使用的页面。 http://robertnyman.com/html5/fileapi-upload/fileapi-upload.html

感谢您的帮助 奥利弗

【问题讨论】:

    标签: asynchronous upload asp.net-web-api xmlhttprequest progress-bar


    【解决方案1】:

    似乎其他人向您提出了同样的问题并得到了答案。请查看ASP.NET MVC 4 Web Api ajax file upload。 这是来自 microsoft http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-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);
            }
        }
    }
    

    【讨论】:

    • 感谢您的回复,但遗憾的是我已经看到了 2 个链接。
    猜你喜欢
    • 2013-08-02
    • 2014-05-02
    • 2011-11-16
    • 2022-11-11
    • 2021-07-13
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多