gpt4 book ai didi

c# - 如何返回 MemoryStream docx 文件 MVC?

转载 作者:可可西里 更新时间:2023-11-01 08:55:48 27 4
gpt4 key购买 nike

我有一个 docx 文件,我想在编辑后返回该文件。我有以下代码...

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"));

文件看起来不错,但我收到错误消息(“文件已损坏”和另一条消息“Word 发现无法读取的内容。如果您信任来源,请单击是”)。有什么想法吗?

提前致谢

编辑

这是我模型中的 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;
}
}

最佳答案

我使用 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");

关于c# - 如何返回 MemoryStream docx 文件 MVC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14630336/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com