2016-09-08 41 views
0

我遇到問題。我有docx文件存儲爲數據庫中的字節數組。我需要得到這個文件的網址。網址應該像http://my-site.com ...但我不知道我怎麼能達到它。我用內存流,文件流等閱讀了許多主題,但我仍不明白我如何達到這個目標。我寫在ASP MVC C#中。如何從字節數組中獲取url?

+0

我想你的意思該URL在文檔中?效率不是很高,但如果對字節的理解不夠深入,則可以將文檔轉換爲字符串,然後使用方法進行搜索,以瞭解如何使用。 http://stackoverflow.com/questions/11654562/how-convert-byte-array-to-string –

回答

3

對於ASP.NET MVC部分,您可以使用控制器的File方法來返回字節數組作爲文件下載,就像本例中一樣。

public class HomeController : Controller 
{   
    public ActionResult Download(string id) 
    { 
     byte[] fileInBytes = GetFileDataFromDatabase(id); 

     return File(fileInBytes, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", 
      id + ".docx"); 
    } 

    private byte[] GetFileDataFromDatabase(string id) 
    { 
     // your code to access the data layer 

     return byteArray; 
    } 
} 

的網址是:http://.../home/download/{someId}

+0

我應該能夠執行下載後下載文件?我沒有結果。 如何獲取此Url? 對不起愚蠢的問題,但工作wirh文件是非常困難的。 – smile

+0

我剛剛執行我的示例與URL(根據默認的MVC路由)http:// localhost:.../home/download/1234和瀏覽器提示我一個下載對話框。但這僅僅是一個示例 - 如果它不起作用,請張貼您的控制器的一些代碼。 –

1

事情是這樣的:

[HttpGet] 
[Route("file/{fileId}")] 
public HttpResponseMessage GetPdfInvoiceFile(string fileId) 
     { 
      var response = Request.CreateResponse(); 
      //read from database 
      var fileByteArray= ReturnFile(fileId); 
      if (fileByteArray == null) throw new Exception("No document found"); 
       response.StatusCode = HttpStatusCode.OK; 
       response.Content = new StreamContent(new MemoryStream(fileByteArray)); 
       response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition"); 
       response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") 
       { 
        FileName = fileId+ ".docx" 
       }; 
       response.Content.Headers.ContentType = 
        new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); 
       response.Headers.Add("Content-Transfer-Encoding", "binary"); 
       response.Content.Headers.ContentLength = fileByteArray.Length; 
       return response; 

    } 

,或者如果你有一個剃刀的mvc網站只需使用FileResult:Download file of any type in Asp.Net MVC using FileResult?

+0

這個實現是用於休息api的,現在是一個簡單的解釋:因爲你正在從DB讀取shebang,所以一旦響應離開控制器,就需要保持它可供客戶端使用(保存在內存中或磁盤上以供使用由客戶),更多細節:http://stackoverflow.com/questions/8156896/difference-between-memory-stream-and-filestream – SilentTremor

+0

我不好,我用了兩個內存流:),更新 – SilentTremor