gpt4 book ai didi

c# - WebAPI 返回损坏的、不完整的文件

转载 作者:行者123 更新时间:2023-11-30 18:17:06 31 4
gpt4 key购买 nike

我想从 WebApi 端点返回图像。这是我的方法:

[System.Web.Http.HttpGet]
public HttpResponseMessage GetAttachment(string id)
{
string dirPath = HttpContext.Current.Server.MapPath(Constants.ATTACHMENT_FOLDER);
string path = string.Format($"{dirPath}\\{id}.jpg");

try
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open, FileAccess.Read);

var content = new StreamContent(stream);
result.Content = content;
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = Path.GetFileName(path) };
return result;
}
catch (FileNotFoundException ex)
{
_log.Warn($"Image {path} was not found on the server.");
return Request.CreateResponse(HttpStatusCode.NotFound, "Invalid image ID");
}
}

很遗憾,下载的文件不完整。使用 Android 应用程序时的消息是:

java.io.EOFException: source exhausted prematurely

最佳答案

问题很可能是您的 Android 客户端认为下载已经结束,但实际上尚未结束。
要轻松解决此问题,您可以改用此方法,它会立即返回整个文件(而不是流式传输):

result.Content = new ByteArrayContent(File.ReadAllBytes(path));

关于c# - WebAPI 返回损坏的、不完整的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44925841/

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