【发布时间】:2020-05-25 00:11:04
【问题描述】:
我想用我的控制器下载一个文件:
public HttpResponseMessage GetFileConverted(string fileName)
{
if (String.IsNullOrEmpty(fileName))
return Request.CreateResponse(HttpStatusCode.BadRequest);
string filePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Uploads/");
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new FileStream((filePath + fileName), FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
我做了一个测试:
但由于文件扩展名为 .pdf,它无法正常工作 例如,当我的文件名等于“测试”时,它正在工作。但是,当我尝试放入“.pdf”时,它会产生问题。
所以我把我的控制器改成了这个:
public HttpResponseMessage GetFile(string fileName)
{
if (String.IsNullOrEmpty(fileName))
return Request.CreateResponse(HttpStatusCode.BadRequest);
string filePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Uploads/");
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new FileStream((filePath + fileName + ".pdf"), FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName + ".pdf";
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
现在我只是把我的文件名不带扩展名放在我的网址中下载他。
但我认为有更好的方法来解决此类问题。你能给我建议或文件吗?因为没有发现任何关于这个问题的信息。
【问题讨论】:
-
我认为您尝试调用的 uri 应该是 .../GetFile?filename=test.pdf
标签: c# asp.net asp.net-mvc visual-studio asp.net-web-api