如何将网页上生成的文件作为下载提供给用户? [英] How can I make a file generated on a web page available to the user as a download?

查看:225
本文介绍了如何将网页上生成的文件作为下载提供给用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题与我提出的问题有关此处如何从Sharepoint页面提示用户输入保存位置?

This question is related to one I asked here on "How can I prompt the user for a save location from a Sharepoint page?"

我需要做什么因此,在生成PDF之后:

What I need to do is, after generating a PDF thus:

        private void GeneratePDF(List<ListColumns> listOfListItems)
        {
            . . .
            //Create a stream that we can write to, in this case a MemoryStream
            StringBuilder sb = new StringBuilder();
            using (var ms = new MemoryStream())
            {
                using (var doc = new Document(PageSize.A4, 25, 25, 10, 10)) 
                {
                    //Create a writer that's bound to our PDF abstraction and our stream
                    using (var writer = PdfWriter.GetInstance(doc, ms))
                    {

                        //Open the document for writing
                        doc.Open();

                        Paragraph docTitle = new Paragraph("UCSC - Direct Payment Form", timesBold16UCSCBlue);
                        doc.Add(docTitle);

                        Paragraph subTitle = new Paragraph("(Not to be used for reimbursement of services)", timesRoman9Font);
                        subTitle.IndentationLeft = 20;
                        doc.Add(subTitle);

                        . . . // tons of iTextSharp PDF-generation code elided for brevity

                        String htmlToRenderAsPDF = sb.ToString();

                        //XMLWorker also reads from a TextReader and not directly from a string
                        using (var srHtml = new StringReader(htmlToRenderAsPDF))
                        {
                            XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
                        }

                        doc.Close();
                    }
                }
                try
                {
                    var bytes = ms.ToArray();
                    // This is currently saved to a location on the server such as C:\Users\TEMP.SP.005\Desktop\iTextSharpTest.pdf (but the number (such as 
"005" irregularly increments))
                    String pdfFileID = GetYYYYMMDDAndUserNameAndAmount();
                    String pdfFileName = String.Format("DirectPayDynamic_{0}.pdf", pdfFileID);
                    String fileFullpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), pdfFileName);
                    String fileLinkBase = "Generated PDF: <a href=\"{0}\">{1}</a>";
                    String filelink = String.Format(fileLinkBase, fileFullpath, pdfFileName);
                    File.WriteAllBytes(fileFullpath, bytes);

                    var pdflink = new Label
                    {
                        CssClass = "finaff-webform-field-label",
                        Text = filelink
                    };
                    this.Controls.Add(pdflink);
                }
                catch (DocumentException dex)
                {
                    throw (dex);
                }
                catch (IOException ioex)
                {
                    throw (ioex);
                }
                catch (Exception ex)
                {
                    throw (ex);
                }
            }
        } // GeneratePDF

...让用户有机会将该文件保存到本地计算机(目前,它正在保存在服务器上)。

...afford the user the opportunity to save that file to their local machine (currently, it is being saved on the server).

IOW,我基本上想要做的就是替换这一行:

IOW, what I basically want to do is replace this line:

String fileFullpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), pdfFileName);

...类似于:

String fileFullpath = "Hey, bloke (or blokette), where do you want to save this?"

这显然是可能的,甚至有点普遍,因为很多网站会为你生成文件然后允许您将这些

This is obviously possible, and even somewhat common, as many websites will generate files for you and then allow you to save those

生成的文件保存到您选择的位置或默认位置,例如您的下载文件夹。

generated files to either a location you select or a default location, such as your downloads folder.

服务器端(C#)或客户端(jQuery)解决方案都是可以接受的,虽然我更喜欢服务器端,因为这是生成PDF的地方。

Either a server-side (C#) or a client-side (jQuery) solution is acceptable, although I prefer server-side, as that is where the PDF is being generated.

推荐答案

当我不得不强制将Excel电子表格下载到客户端时,我使用了这段代码,这可能会指向您想要获得的位置:

When I had to force an Excel spreadsheet to download to the client, I used this code, which may point you to where you are wanting to get:

LinkBut​​ton类型的控件xxx必须放在带有runat = server <的表单标签内/ a>

Control xxx of type 'LinkButton' must be placed inside a form tag with runat=server

protected void ExportExcelFile(object Sender, EventArgs e) { //export to excel
        var grdResults = new DataGrid(); // REF: https://stackoverflow.com/q/28155089/153923
        if (periodCriteria.SelectedValue == "year") {
            grdResults = RollupDG;
        } else {
            grdResults = QuarterDG;
        }
        var response = HttpContext.Current.Response;
        response.Clear();
        response.Charset = String.Empty;
        response.ContentType = "application/vnd.ms-excel";
        response.AddHeader("Content-Disposition", "attachment; filename=GlBudgetReport.xls");
        using (var sw = new StringWriter()) {
            using (var htw = new HtmlTextWriter(sw)) {
                grdResults.RenderControl(htw);
                response.Write(sw.ToString());
                response.End();
            }
        }
}

这篇关于如何将网页上生成的文件作为下载提供给用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆