将文件读取为字节时不支持URI格式?

时间:2019-05-09 18:55:14

标签: c# asp.net-web-api

我正在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);
        }
    }

1 个答案:

答案 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")));
        }