简体   繁体   English

使用ServiceStack下载文件HttpResult:如何为下载的内容指定文件名?

[英]Download a file with ServiceStack HttpResult: how to specify a file name for downloaded content?

I am using ServiceStack for a simple web application. 我正在使用ServiceStack来创建一个简单的Web应用程序。 The main purpose is to let a user download a file. 主要目的是让用户下载文件。 I am using an HttpResult as follows: 我正在使用HttpResult如下:

public class FileDownloadService : Service
{
 public object Any()
 {
  string fileFullPath = "...";
  string mimeType = "application/pdf";
  FileInfo fi = new FileInfo(fileFullPath);

  byte[] reportBytes = File.ReadAllBytes(fi.FullName);
  result = new HttpResult(reportBytes, mimeType);

  return result;
 }
}

This opens a dialog in the user's browser and the user can specify where to save the file. 这将在用户的浏览器中打开一个对话框,用户可以指定保存文件的位置。 A default name is specified, which is the name of the restPath of ServiceStack. 指定了默认名称,即ServiceStack的restPath的名称。

My question is: is it possible to specify a custom file name for when the user chooses to save (changing the default one)? 我的问题是:是否可以为用户选择保存(更改默认值)时指定自定义文件名? I tried to work with HttpResult properties, but no luck. 我尝试使用HttpResult属性,但没有运气。 Thanks in advance! 提前致谢!

You should set the 'Content-Disposition' header on the HTTP result. 您应该在HTTP结果上设置“Content-Disposition”标头。 That allows to set the filename: 这允许设置文件名:

 public object Any()
 {
     string fileFullPath = "...";
     string mimeType = "application/pdf";
     FileInfo fi = new FileInfo(fileFullPath);

     byte[] reportBytes = File.ReadAllBytes(fi.FullName);
     result = new HttpResult(reportBytes, mimeType);

     result.Headers.Add("Content-Disposition", "attachment;filename=YOUR_NAME_HERE.pdf;");    

     return result;
 }

I have found the solution. 我找到了解决方案。 I was deceived by the readonly properties of the HttpResult. 我被HttpResult的只读属性所欺骗。 In order to change the default file name, I discovered that I have to add the following line, that treats the content-disposition: 为了更改默认文件名,我发现我必须添加以下行来处理内容处置:

result.Headers[HttpHeaders.ContentDisposition] = "attachment; filename=\"UserSurname_UserName.pdf\"";

Thank you all for your time! 谢谢大家的时间!

If I understood your question correctly, what you want is the user wants to rename the file. 如果我正确理解了您的问题,您想要的是用户想要重命名该文件。 This is nothing to do with the server. 这与服务器无关。 The user has to do some changes in the brwoser he is uses. 用户必须对他使用的brwoser进行一些更改。

eg Firefox - Tools > Options > General 例如Firefox - 工具>选项>常规

Then check the "Always ask me where to save files" 然后检查“总是问我在哪里保存文件”

Chrome - Settings > Downloads Chrome - 设置>下载

Then check the "Ask where to save each file before " 然后检查“询问之前保存每个文件的位置”

Then it will open file browser where to save, you may change your file name what ever your wanted 然后它将打开文件浏览器保存的位置,您可以根据需要更改文件名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM