ASP.net download and save file in user folder

荒凉一梦 提交于 2019-12-08 08:57:37

问题


I am trying to save a file to the user pc but I am not able to do it. This method gives error since is trying to save the file in C somewhere. I understand it is not approriate. I would like to save the file in the download folder or prompt the user with a file dialog.

void SaveReport(Telerik.Reporting.Report report, string fileName)
{
    ReportProcessor reportProcessor = new ReportProcessor();
    Telerik.Reporting.InstanceReportSource instanceReportSource = new Telerik.Reporting.InstanceReportSource();
    instanceReportSource.ReportDocument = report;
    RenderingResult result = reportProcessor.RenderReport("PDF", instanceReportSource, null);

    using (FileStream fs = new FileStream(fileName, FileMode.Create))
    {
        fs.Write(result.DocumentBytes, 0, result.DocumentBytes.Length);
    }
}

How can I save the file in the download folder of the user machine or prompt a filedialog to allow the user to choose the destination?


回答1:


You can't force the place the file is downloaded to.

In your code, you shouldn't write to file, but to the OutputStream from the response.

RenderingResult result = reportProcessor.RenderReport("PDF", instanceReportSource, null);

HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"file.pdf\"");
HttpContext.Current.Response.OutputStream.Write(result.DocumentBytes, 0, result.DocumentBytes.Length);



回答2:


Filestream will write to a file on server and not on the client's machine.

Try writing the document bytes to response output stream and a content-disposition http header to response.

Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

This would prompt user for the file download based on browser setting.

You cannot control which directory file goes in in the client's machine.



来源:https://stackoverflow.com/questions/24593783/asp-net-download-and-save-file-in-user-folder

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