【发布时间】:2018-01-29 18:16:18
【问题描述】:
我正在努力使用基于从 WebAPI 返回的字节数组的数据创建文件。以下是我调用 web api 的代码
using (var http = new WebClient())
{
string url = string.Format("{0}api/FileUpload/FileServe?FileID=" + fileID, webApiUrl);
http.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
http.Headers[HttpRequestHeader.Authorization] = "Bearer " + authCookie.Value;
http.DownloadDataCompleted += Http_DownloadDataCompleted;
byte[] json = await http.DownloadDataTaskAsync(url);
}
api代码是
[HttpGet]
[Route("FileServe")]
[Authorize(Roles = "Admin,SuperAdmin,Contractor")]
public async Task<HttpResponseMessage> GetFile(int FileID)
{
using (var repo = new MBHDocRepository())
{
var file = await repo.GetSpecificFile(FileID);
if (file == null)
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
var stream = File.Open(file.PathLocator, FileMode.Open);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(file.FileType);
return response;
}
}
我收到一个字节数组作为响应,但是我无法从该字节数组创建相应的文件。我不知道如何将字节数组转换为相关的文件类型(例如 jpg 或基于 web api 中文件类型的 pdf)。任何帮助将不胜感激。
【问题讨论】:
-
所以你在字段 json 中有一个字节数组,是你的文件,但你不明白如何保存该文件?比如你发了一张png格式的图片,那个字节数组就是图片,你要保存到硬盘吗?
-
网站和 web api 位于两个不同的端点上,因此我想从 web api 通过网站下载文档并将其保存到文件夹中。希望你明白我的意思
-
stackoverflow.com/a/6397249/5947043 向您展示如何将字节数组保存到文件中。您可能只需要从标头中读取 MIME 类型来决定为其提供什么扩展名。不知道您为什么将变量命名为
json,因为显然不是。 -
变量“byte[] json”只是一个名字,反馈应该以字节为单位
-
嗯,我认为你在 WebClient 上使用了错误的方法,像 OpenRead 这样的东西呢,它返回一个流,然后你可以查看结果并找到它的 mime 类型
标签: c# asp.net asp.net-web-api