2013-01-31 70 views
7

我有一個docx文件,我想在編輯後返回。我有以下代碼...如何返回MemoryStream docx文件MVC?

object useFile = Server.MapPath("~/Documents/File.docx"); 
object saveFile = Server.MapPath("~/Documents/savedFile.docx"); 
MemoryStream newDoc = repo.ChangeFile(useFile, saveFile); 
return File(newDoc.GetBuffer().ToArray(), "application/docx", Server.UrlEncode("NewFile.docx")); 

該文件似乎不錯,但我收到錯誤消息(「文件被損壞」,另一個聲稱「字中找到不可讀的內容。如果您信任源單擊Yes」 )。有任何想法嗎?提前

感謝

編輯

這是ChangeFile在我的模型......

public MemoryStream ChangeFile(object useFile, object saveFile) 
    { 
     byte[] byteArray = File.ReadAllBytes(useFile.ToString()); 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      ms.Write(byteArray, 0, (int)byteArray.Length); 
      using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(ms, true)) 
      {      
       string documentText; 
       using (StreamReader reader = new StreamReader(wordDoc.MainDocumentPart.GetStream())) 
       { 
        documentText = reader.ReadToEnd(); 
       } 

       documentText = documentText.Replace("##date##", DateTime.Today.ToShortDateString()); 
       using (StreamWriter writer = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create))) 
       { 
        writer.Write(documentText); 
       } 
      } 
      File.WriteAllBytes(saveFile.ToString(), ms.ToArray()); 
      return ms; 
     } 
    } 
+2

您是否可以直接在Word中的「〜/ Documents/savedFile.docx」中打開文件而無需下載?如果是,則問題是不完整/損壞的下載。如果不是,你需要告訴我們'repo.ChangeFile'裏面發生了什麼。 –

+0

從您的描述中可以看出,您所做的更改沒有正確完成。 –

+2

請注意,有一個'MemoryStream.ToArray()'方法,您不需要使用'GetBuffer()'。 – Lloyd

回答

13

我使用FileStreamResult

var cd = new System.Net.Mime.ContentDisposition 
    { 
     FileName = fileName, 

     // always prompt the user for downloading, set to true if you want 
     // the browser to try to show the file inline 
     Inline = false, 
    }; 
Response.AppendHeader("Content-Disposition", cd.ToString()); 

return new FileStreamResult(documentStream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); 
6

不要使用MemoryStream.GetBuffer().ToArray()使用MemoryStream.ToArray()

爲什麼是GetBuffer()的原因涉及用於創建存儲器流的數組,而不是存儲器流中的實際數據。底層陣列的大小實際上可能不同。

隱藏在MSDN:

注意,緩衝區包含分配的字節,這可能是未使用的。 例如,如果將字符串「test」寫入到MemoryStream 對象中,則從GetBuffer返回的緩衝區的長度爲256,而不是 4,未使用252個字節。要僅獲取緩衝區中的數據,請使用ToArray方法 ;但是,ToArray會在內存中創建數據的副本。

+0

你的答案解決了我的錯誤:我使用了GetBuffer,並在最後一行得到了一大串NULL。用ToArray替換GetBuffer解決了它!謝謝! – Alonzzo2