如何通过C# Web API中的FileStreamResult更改下载文件的名称?

huangapple go评论82阅读模式
英文:

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(&quot;GetCSV&quot;)]
public async Task&lt;ActionResult&lt;FileStreamResult&gt;&gt; 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, &quot;text/csv&quot;);
	}
	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=&quot;somethingElse.csv&quot;

当指定了FileDownloadName属性时,FileResult返回此头:

return new FileStreamResult(stream, &quot;text/csv&quot;)

    FileDownloadName = &quot;somethingElse.csv&quot;;
};```

<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>



huangapple
  • 本文由 发表于 2023年6月6日 16:59:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76412983.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定