虽然这已被标记为已回答,但这并不是我想要的,所以我一直在寻找。现在我已经弄清楚了,这就是我所拥有的:
public FileContentResult GetFile(string id)
{
byte[] fileContents;
using (MemoryStream memoryStream = new MemoryStream())
{
using (Bitmap image = new Bitmap(WebRequest.Create(myURL).GetResponse().GetResponseStream()))
image.Save(memoryStream, ImageFormat.Jpeg);
fileContents = memoryStream.ToArray();
}
return new FileContentResult(fileContents, "image/jpg");
}
当然,这是为了通过 URL 获取图像。如果您只想从文件服务器中获取图像,我想您替换此行:
using (Bitmap image = new Bitmap(WebRequest.Create(myURL).GetResponse().GetResponseStream()))
有了这个:
using (Bitmap image = new Bitmap(myFilePath))
编辑:没关系,这是针对常规 MVC 的。对于 Web API,我有这个:
public HttpResponseMessage Get(string id)
{
string fileName = string.Format("{0}.jpg", id);
if (!FileProvider.Exists(fileName))
throw new HttpResponseException(HttpStatusCode.NotFound);
FileStream fileStream = FileProvider.Open(fileName);
HttpResponseMessage response = new HttpResponseMessage { Content = new StreamContent(fileStream) };
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
response.Content.Headers.ContentLength = FileProvider.GetLength(fileName);
return response;
}
这与OP所拥有的非常相似。