我正在asp.net Web API框架中制作API。我想读取文件并将其转换为字节并返回给客户端。但是读取文件时会发生异常,不支持URL格式吗? 带有文件名的URL是由客户端发送的。我想从该URL获取文件并将其转换为字节。告诉我,我该怎么做?
[Route("api/product/v1/displayimage")]
[AllowAnonymous]
[HttpPost]
//[GZipCompression]
public async Task<byte[]> DisplayImage([FromBody] FilesVM model)
{
try
{
var UrlBase = Url.Content(model.BaseURL);
//var UrlBase = Url.Content("~/Images/Users/5-signs-march14");
// MemoryStream workStream = new MemoryStream();
//string contentType = MimeMapping.GetMimeMapping(fileName);
byte[] byteInfo = System.IO.File.ReadAllBytes(UrlBase);
return await Task.FromResult(byteInfo);
}
catch (Exception ex)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
}
答案 0 :(得分:0)
Url.Content仅返回字符串(http://localhost/Image..。)。如果您需要实际的内容,则必须下载。这是一个示例:
using (var client = new WebClient())
{
return await Task.FromResult(client.DownloadData(Url.Content("~/Images/Users/5-signs-march14")));
}