我正在使用WebAPI下载.pdf
文件,如下所示:
[HttpGet]
public async Task<HttpResponseMessage> DownloadFile(string id, bool attachment = true)
{
HttpResponseMessage result = null;
try
{
MyService service = new MyService();
var bytes = await service.DownloadFileAsync(id);
if (bytes != null)
{
result = GetBinaryFile(personalDocument, string.Format("{0}.pdf", id), attachment);
}
else
{
result = new HttpResponseMessage(HttpStatusCode.NotFound);
}
}
catch (Exception ex)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest) { ReasonPhrase = "ServerError" });
}
return result;
}
private HttpResponseMessage GetBinaryFile(byte[] bytes, string fileName, bool attachment)
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
// result.Content = new ByteArrayContent(bytes);
result.Content = new StreamContent(new System.IO.MemoryStream(bytes));
//result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline");
if (attachment)
{
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
}
result.Content.Headers.ContentDisposition.FileName = fileName;
result.Content.Headers.ContentLength = bytes.Length;
return result;
}
问题是:当我第一次下载文件时,它会冻结浏览器,并且无法执行任何操作。但刷新页面后,每次文件下载成功。
我尝试使用ByteArrayContent
或StreamContent
,但同样的事情发生了。我还尝试使用MediaTypeHeaderValue("application/octet-stream")
或MediaTypeHeaderValue("application/pdf")
,但又一次 - 发生了同样的问题。
所以我发现问题是
if (attachment)
{
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
}
如果我将附件设置为true,则将ContentDisposition
设置为ContentDispositionHeaderValue("attachment")
(仅供下载)
如果我将附件设置为false,则立即打开文件,不会冻结浏览器..
有什么想法吗?谢谢!