如何在浏览器中打开文件而不是使用 WebAPI 下载 ASP.NET?



我的当前代码如下,它只下载文件。如何在浏览器中查看所有文件类型?

[HttpGet]
//[NoCacheHeader()]
[Route("api/image/files")]
public HttpResponseMessage GFiles(string ImageName)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
var path = "~/Image/" + ImageName;
path = System.Web.Hosting.HostingEnvironment.MapPath(path);
var ext = System.IO.Path.GetExtension(path);
var contents = System.IO.File.ReadAllBytes(path);
System.IO.MemoryStream ms = new System.IO.MemoryStream(contents);
response.Content = new StreamContent(ms);
//
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = ImageName;
//
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("Image/" + ext);
return response;
}

我只找到了pdf和图像的解决方案。只需在 MediaTypeHeaderValue 中添加 MIME 类型,并确保 ContentDispositionHeaderValue 是"内联的">

response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("inline");

对于 pdf:

response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");

对于图像:

response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("images/jpeg");

根据图像类型改变您的 MIME。 对于微软文档,请在MediaHeaderValue中使用它的MIME类型,然后在Google Chrome中安装离线Google Docs扩展程序

只是稍微补充一下接受的答案:附件意味着下载,内联意味着打开。 但是浏览器还需要知道它打开的类型以防止下载。

此外,您还可以在是从其他 Web 服务获取内容之间切换,还是使用注释行通过流获取内容。

因此,如果您想在浏览器中打开从另一个网络服务获得的pdf,它将如下所示:

var result = new HttpResponseMessage(HttpStatusCode.OK)
{
//Content = new ByteArrayContent(stream.ToArray())
Content = new ByteArrayContent(response.RawBytes)
};
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("inline") //attachment
{
FileName = fileName
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); //images/jpeg
return result;

最新更新