Return files in ASP.NET MVC for viewing or downloading
In ASP.NET MVC, returning files stored in the database to users may bring challenges. The goal is to provide two options: Mimetype determined by the browser is viewed by the browser to view files and forced download files by the browser, regardless of the file type.
File processing options
FilestreamResult class is usually used to send files. However, it cannot specify the file name by default, which will lead to unexpected behaviors when dealing with the expansion of the unknown file. Forced specified file names can make the browser unable to open the file directly.
In order to solve this problem, we can use the ContentDisposition class and set the Filename property to the actual name of the document. In addition, set the Inline property to FALSE to prompt the browser to download the file instead of trying to open it.
code example
The following is an example implementation in ASP.NET CORE (complete framework). The implementation also solves the problem of international character processing:
public ActionResult Download()
{
Document document = ...; // 获取文件数据
var cd = new ContentDispositionHeaderValue("attachment")
{
FileNameStar = document.FileName // 使用 FileNameStar 属性处理文件名中的特殊字符
};
Response.Headers.Add(HeaderNames.ContentDisposition, cd.ToString());
return File(document.Data, document.ContentType); // 返回文件数据和内容类型
}
Copy after login
By using the ContentDispositionHeaderValue class, we can ensure that the international characters in the file name are properly handled. This method allows viewing and downloading files, and determines the required behavior based on the premiere of the browser.
The above is the detailed content of How to Return Files for Viewing or Downloading in ASP.NET MVC?. For more information, please follow other related articles on the PHP Chinese website!