Answer the question
In order to leave comments, you need to log in
How to solve the problem: Response does not return .docx for download to the user's browser?
Good afternoon. I am developing a method on ASP.NET-WebForms. The bottom line is this: the user presses a button, a piece of data is formed on the front, which is transferred to the handler on the back. Additional data is selected in the handler, a .docx template is opened, edited using OpenXML tools, and the contents of the resulting file are written to a MemoryStream, which must be returned to the user in Response. Here is the handler code without editing the document itself, declaring and initializing variables.
//Объявление и инициализация переменных
byte[] FileBytes = File.ReadAllBytes(Template);
using (MemoryStream stream = new MemoryStream(FileBytes))
{
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(stream, true))
{
MainDocumentPart mainPart = myDoc.MainDocumentPart;
foreach (SdtElement obj in mainPart.Document.Body.Descendants<SdtElement>().ToList())
{
foreach (Text t in obj.Descendants<Text>().ToList())
{
switch (t.Text)
{
//.... редактирование файла .docx
}
}
}
myDoc.MainDocumentPart.Document.Save();
myDoc.Close();
}
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.AddHeader("content-disposition", "attachment; filename=\"" + DocName + ".docx\"");
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
context.Response.ContentEncoding = Encoding.GetEncoding("ISO-8859-1");
stream.Seek(0, SeekOrigin.Begin);
context.Response.BinaryWrite(stream.ToArray());
}
context.Response.Flush();
function save_word_doc(id_btn) {
// ... here is code that gets params from default page data
jQuery.post("DataHandler.ashx?CN=" + vCN + "&CommandName=SaveWord&auctionID=" + oFormRecord.auctionID
+ "&user_login=" + user_login
+ ....
+ "&amount=" + oFormRecord.value.amount
+ "&percent=" + percent);
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question