Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将生成的文件保存在服务器上,而不是在C中作为下载给用户#_C#_Html_Asp.net_Ms Word - Fatal编程技术网

C# 将生成的文件保存在服务器上,而不是在C中作为下载给用户#

C# 将生成的文件保存在服务器上,而不是在C中作为下载给用户#,c#,html,asp.net,ms-word,C#,Html,Asp.net,Ms Word,我有以下方法,它将HTML转换为Word文档并将其作为下载发送给用户 public static void HtmlToWordDownload(string HTML, string FileName, string title = "", bool border = false) { lock (LockMulti) { string strBody = string.Empty; strBody = @"<html xmlns:o='u

我有以下方法,它将HTML转换为Word文档并将其作为下载发送给用户

public static void HtmlToWordDownload(string HTML, string FileName, string title = "", bool border = false)
{
    lock (LockMulti)
    {
        string strBody = string.Empty;
        strBody = @"<html xmlns:o='urn:schemas-microsoft-com:office:office' " +
        "xmlns:w='urn:schemas-microsoft-com:office:word'" +
        "xmlns='http://www.w3.org/TR/REC-html40'>" +
        "<head><title>:" + title + "</title>" +
         "<!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:Zoom>100</w:Zoom>" +
         "<w:DoNotOptimizeForBrowser/></w:WordDocument></xml><![endif]-->" +
         "<style> @page Section1 {size:8.27in 11.69in; mso-first-footer:ff1; mso-footer: f1; mso-header: h1; " +
         ((border == true) ? "border:solid navy 2.25pt; padding:24.0pt 24.0pt 24.0pt 24.0pt; " : "") +
         "margin:0.6in 0.6in 0.6in 0.6in ; mso-header-margin:.1in; " +
         "mso-footer-margin:.1in; mso-paper-source:0;} " +
         "div.Section1 {page:Section1;} p.MsoFooter, li.MsoFooter, " +
         "div.MsoFooter{margin:0in; margin-bottom:.0001pt; " +
         "mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; " +
         "font-size:12.0pt; font-family:'Arial';} " +
         "p.MsoHeader, li.MsoHeader, div.MsoHeader {margin:0in; " +
         "margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center " +
         "3.0in right 6.0in; font-size:12.0pt; font-family:'Arial';}--></style></head> ";
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Charset = "";
        HttpContext.Current.Response.ContentType = "application/vnd.ms-word";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + FileName + ".doc");
        StringBuilder htmlCode = new StringBuilder();
        htmlCode.Append(strBody);
        htmlCode.Append("<body><div class=Section1>");
        htmlCode.Append(HTML);
        htmlCode.Append("</div></body></html>");
        HttpContext.Current.Response.Write(htmlCode.ToString());
        HttpContext.Current.Response.End();
        HttpContext.Current.Response.Flush();
    }
}
publicstaticvoidhtmltoworddownload(字符串HTML,字符串文件名,字符串title=”,boolborder=false)
{
锁(多锁)
{
string strBody=string.Empty;
strBody=@“”+
“:”+标题+“”+
"" +
“@第1页{大小:8.27英寸11.69英寸;mso第一个页脚:ff1;mso页脚:f1;mso页眉:h1;”+
((border==true)?“边框:纯色海军蓝2.25磅;填充:24.0磅24.0磅24.0磅24.0磅;”:“”)+
“页边距:0.6英寸0.6英寸0.6英寸0.6英寸;mso页眉页边距:.1英寸;”+
“mso页脚边距:.1in;mso纸张来源:0;}”+
第1节{页码:第1节;}p.MSOFOTER,li.MSOFOTER+
“div.msofoter{页边距:0in;页边距底部:.0001pt;”+
“mso分页:孤立窗口;制表位:居中3.0英寸右侧6.0英寸;”+
“字体大小:12.0pt;字体系列:'Arial';}”+
p.MsoHeader,li.MsoHeader,div.MsoHeader{边距:0英寸+
“页边距底部:.0001pt;mso分页:孤立页;制表位:中间”+
“右侧3.0英寸;字体大小:12.0磅;字体系列:'Arial';}-->”;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset=“”;
HttpContext.Current.Response.ContentType=“应用程序/vnd.ms word”;
HttpContext.Current.Response.AddHeader(“内容处置”、“内联;文件名=“+filename+”.doc”);
StringBuilder htmlCode=新的StringBuilder();
htmlCode.Append(strBody);
htmlCode.追加(“”);
附加(HTML);
htmlCode.追加(“”);
HttpContext.Current.Response.Write(htmlCode.ToString());
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
}
}

现在我不想直接把它作为下载给用户,我想先把它保存在我服务器的本地文件夹中,然后作为下载给用户。我该怎么做呢?

您可以尝试在执行htmlCode.ToString()时像这样提供生成的文件:

另一种方法是保存文件并将其作为字节数组读取,然后按如下方式提供:

byte[] Content= File.ReadAllBytes(FilePath); //missing ;
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();
Response.Redirect("PathToHttpHandler/DownloadFile.ashx?yourVariable=yourValue");
System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
string yourVariableValue = request.QueryString["yourVariable"];

// Use the yourVariableValue here

否则

将word/pdf文件保存到服务器上的某个临时路径后,可以使用HTTP处理程序(.ashx)下载文件,如下所示:

byte[] Content= File.ReadAllBytes(FilePath); //missing ;
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();
Response.Redirect("PathToHttpHandler/DownloadFile.ashx?yourVariable=yourValue");
System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
string yourVariableValue = request.QueryString["yourVariable"];

// Use the yourVariableValue here
ExamplePage.ashx:

public class DownloadFile : IHttpHandler 
{
    public void ProcessRequest(HttpContext context)
    {   
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.ClearContent();
        response.Clear();
        response.ContentType = "text/plain";
        response.AddHeader("Content-Disposition", 
                           "attachment; filename=" + fileName + ";");
        response.TransmitFile(Server.MapPath("FileDownload.csv"));
        response.Flush();    
        response.End();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
然后可以从按钮单击事件处理程序调用HTTP处理程序,如下所示:

byte[] Content= File.ReadAllBytes(FilePath); //missing ;
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();
Response.Redirect("PathToHttpHandler/DownloadFile.ashx?yourVariable=yourValue");
System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
string yourVariableValue = request.QueryString["yourVariable"];

// Use the yourVariableValue here
标记:

<asp:Button ID="btnDownload" runat="server" Text="Download File" 
            OnClick="btnDownload_Click"/>
将参数传递给HTTP处理程序:

您只需将查询字符串变量附加到Response.Redirect(),如下所示:

byte[] Content= File.ReadAllBytes(FilePath); //missing ;
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();
Response.Redirect("PathToHttpHandler/DownloadFile.ashx?yourVariable=yourValue");
System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
string yourVariableValue = request.QueryString["yourVariable"];

// Use the yourVariableValue here
然后在实际的处理程序代码中,您可以使用HttpContext中的请求对象来获取查询字符串变量值,如下所示:

byte[] Content= File.ReadAllBytes(FilePath); //missing ;
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();
Response.Redirect("PathToHttpHandler/DownloadFile.ashx?yourVariable=yourValue");
System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
string yourVariableValue = request.QueryString["yourVariable"];

// Use the yourVariableValue here

注意-通常会将文件名作为查询字符串参数传递给用户,以向用户建议文件的实际内容,在这种情况下,用户可以使用“另存为…”覆盖该名称值。

您是否收到任何特定错误,或者您的代码正在执行编码的操作,但您不知道该执行什么操作?没有错误,图像不会出现并显示“X”,所以现在我想知道,在我的第一种方法中,不是下载word文档,是否有办法将其保存在web服务器上的文件夹中我的疑问是如何强制响应。写入以将文件保存在我的服务器上,而不是将其下载给用户。@PrasanthKumarVinakota只需使用标准的C#save file例程,使用async/await转换为pdf,然后返回pdf文件即可。要将文件保存到正确的路径,请使用Server.MapPathYa,我尝试了几个小时,但没有正确地保存。我尝试了这个流文件=file.Create(System.Web.HttpContext.Current.Server.MapPath(“~/TempFiles/”+FileName+”.doc”);流rs=HttpContext.Current.Response.OutputStream;rs.CopyTo(文件);file.Close(),它说OutPutStream不可读