2

我試圖用進度條拖放文件上傳。Web API異步使用XmlHttpRequest上傳以獲取進度

我有一個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(); 
} 

我想有機會的要求,即「公共異步任務<字符串>發佈(){}

如果方法,使用的頁面,而不是XmlHttpRequest的一個多形式,我會用「等待Request.Content.ReadAsMultipartAsync(提供者)」,但這似乎並沒有填充在我需要它的時間

那麼是正確的是處理和XmlHttpRequest在Web API中的異步調用爲了在XHR進展事件請求期間記錄進度?

我已經查看了很多頁面以找到解決方案,但這是我主要使用的頁面。 http://robertnyman.com/html5/fileapi-upload/fileapi-upload.html

感謝所有幫助 奧利弗

回答

2

它看起來像別人有同樣的問題與你得到了一個答案。請看看ASP.NET MVC 4 Web Api ajax file upload。 這裏是微軟http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2的一個例子。

我一起結合上述兩種解決方案,爲我工作(只是調整一點點)

  1. 一行變化Javascritp

    xhr.open( 「後」,「API /上傳「,是);

  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); 
     } 
    } 
} 
+0

感謝您的答覆保存文件,但可悲的是,我已經看到了2個鏈接。 – Oli