How can I make a file generated on a web page available to the user as a download?

a 夏天 提交于 2019-12-13 01:53:42

问题


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

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, what I basically want to do is replace this line:

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

...with something like:

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.

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.


回答1:


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:

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();
            }
        }
}


来源:https://stackoverflow.com/questions/31544178/how-can-i-make-a-file-generated-on-a-web-page-available-to-the-user-as-a-downloa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!