gpt4 book ai didi

asp.net-web-api - 为什么Web Api HttpResponseMessage不下载文件?

转载 作者:行者123 更新时间:2023-12-02 03:04:48 24 4
gpt4 key购买 nike

我当前正在对 Web Api 方法执行 GET 操作,并将文件名作为参数传递。当我到达该方法时,我的参数已正确解析,并且文件内容正在写入 HttpResponseMessage 对象中的响应内容。

    public HttpResponseMessage Get ([FromUri]string filen)
{
string downloadPath = WebConfigurationManager.AppSettings["DownloadLocation"];

var fileName = string.Format("{0}{1}", downloadPath, filen);
var response = Request.CreateResponse();

if (!File.Exists(fileName))
{
response.StatusCode = HttpStatusCode.NotFound;
response.ReasonPhrase = string.Format("The file [{0}] does not exist.", filen);

throw new HttpResponseException(response);
}

response.Content = new PushStreamContent(async (outputStream, httpContent, transportContext) =>
{
try
{
var buffer = new byte[65536];

using (var file = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
var length = (int)file.Length;
var bytesRead = 1;

while (length > 0 && bytesRead > 0)
{
bytesRead = file.Read(buffer, 0, Math.Min(length, buffer.Length));
await outputStream.WriteAsync(buffer, 0, bytesRead);
length -= bytesRead;
}
}

}
finally
{
outputStream.Close();
}

});

response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = filen
};

return response;
}

似乎什么也没发生,而不是看到正在下载的文件。看来该文件只是丢失了任何地方。我想让浏览器自动下载文件。我确实在fiddler中看到了响应中的内容。所以发生了什么事?任何指示将不胜感激!

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Transfer-Encoding: chunked
Content-Type: application/octet-stream
Expires: -1
Server: Microsoft-IIS/8.0
Content-Disposition: attachment; filename=w-brand.png
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RDpcSnVubGlcQXN5bmNGaWxlVXBsb2FkV2ViQVBJRGVtb1xBc3luY0ZpbGVVcGxvYWRXZWJBUElEZW1vXGFwaVxGaWxlRG93bmxvYWQ=?=
X-Powered-By: ASP.NET
Date: Thu, 12 Feb 2015 19:32:33 GMT
27b5
PNG
...

最佳答案

我不确定,但你可以尝试使用这段代码,它对我有用:

result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "SampleImg";

可能是与您的 PushStreamContent 有关的问题。

在下一个链接中,您可以了解如何从 JavaScript 客户端使用它: How to download memory stream object via angularJS and webaAPI2

希望对您有所帮助。

关于asp.net-web-api - 为什么Web Api HttpResponseMessage不下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28486579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com