英文:
How to change the name of the file downloaded through FileStreamResult in the C# web-api?
问题
这是我的控制器操作。基本上,我正在WebAPI中准备一个CSV文件,然后从UI中下载该文件。
[HttpGet("GetCSV")]
public async Task<ActionResult<FileStreamResult>> GetCSV()
{
var ret = getfile();
return Ok(ret);
}
public FileStreamResult getfile()
{
MemoryStream stream = new MemoryStream();
try
{
// 一些列表操作
string csv = CsvSerializer.SerializeToCsv(list);
stream = GenerateStreamFromString(csv);
return new FileStreamResult(stream, "text/csv");
}
finally
{
stream.Flush();
}
}
public MemoryStream GenerateStreamFromString(string s)
{
byte[] byteArray = Encoding.ASCII.GetBytes(s);
MemoryStream stream = new MemoryStream(byteArray);
return stream;
}
这段代码完全正常工作。从UI调用WebAPI时,文件将以GetCSV.csv的名称下载。
问题是:如何更改文件的名称?
英文:
This is my controller action. Basically I am preparing a CSV file in the WebAPI and from UI the file gets downloaded.
[HttpGet("GetCSV")]
public async Task<ActionResult<FileStreamResult>> GetCSV()
{
var ret = getfile();
return Ok(ret);
}
public FileStreamResult getfile()
{
MemoryStream stream = new MemoryStream();
try
{
//some list
string csv = CsvSerializer.SerializeToCsv(list);
stream = GenerateStreamFromString(csv);
return new FileStreamResult(stream, "text/csv");
}
finally
{
stream.Flush();
}
}
public MemoryStream GenerateStreamFromString(string s)
{
byte[] byteArray = Encoding.ASCII.GetBytes(s);
MemoryStream stream = new MemoryStream(byteArray);
return stream;
}
The code works perfectly fine. From UI, when I call the WebAPI, the file gets downloaded in the name of GetCSV.csv.
The question is: How to change the name of the file?
答案1
得分: 2
服务器必须返回一个Content-Disposition
头,以便客户端知道替代文件名:
Content-Disposition: attachment; filename="somethingElse.csv"
当指定了FileDownloadName
属性时,FileResult
返回此头:
return new FileStreamResult(stream, "text/csv")
FileDownloadName = "somethingElse.csv";
};```
<details>
<summary>英文:</summary>
The server must return a ```Content-Disposition``` header, in order for the client to know about an alternative file name:
Content-Disposition: attachment; filename="somethingElse.csv"
```FileResult``` returns this header when the FileDownloadName property is specified:
return new FileStreamResult(stream, "text/csv")
{
FileDownloadName = "somethingElse.csv"
};
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论