我正在尝试在Chrome中预览文件,但它会继续下载。
[HttpGet]
[ResponseType(typeof(ByteArrayContent))]
public HttpResponseMessage Download([FromUri] int uploadId)
{
try
{
Upload upload = UploadController.LoadByPrimaryKey(uploadId);
var path = upload.FullPath + "\\" + upload.UploadGuid + upload.Extension;
var mimeType = MimeTypeMap.GetMimeType(upload.Extension);
MemoryStream pdf = new MemoryStream(File.ReadAllBytes(path));
HttpResponseMessage result = null;
result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new ByteArrayContent(pdf.ToArray());
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline");
result.Content.Headers.ContentDisposition.FileName = upload.OriginalFileName;
result.Content.Headers.ContentType = new MediaTypeHeaderValue(mimeType);
return result;
}
catch (Exception ex)
{
//..
}
}
这是来自Fiddler的踪迹。
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 793708
Content-Type: application/pdf
Expires: -1
Server: Microsoft-IIS/10.0
Access-Control-Allow-Origin: http://localhost:6701
Access-Control-Allow-Credentials: true
Content-Disposition: inline; filename="1451048-Customer Acceptance.pdf"
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sun, 19 Jun 2016 10:52:35 GMT
...
我见过Open PDF file in browser rather than downloading pdf file和How to force files to open in browser instead of download (pdf)?,但我仍遇到问题。
非常感谢任何帮助。
答案 0 :(得分:1)
我认为您的代码没有任何问题,它看起来更像是您的浏览器设置问题(尽管大多数浏览器都有默认设置来呈现PDF)。
如果在Mozilla中尝试
参考 - https://support.mozilla.org/en-US/kb/disable-built-pdf-viewer-and-use-another-viewer
适用于Chrome
我的API中有完全相同的代码,它允许我根据ContentDispositionHeaderValue渲染PDF或下载(内联渲染和附件下载)
请参阅以下我服务器的响应标题
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 46270
Content-Type: application/pdf
Server: Microsoft-IIS/10.0
Content-Disposition: inline; filename=Sample.pdf
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 20 Jun 2016 03:38:39 GMT
希望这有帮助