我正在尝试制作一个 MVC 应用程序,让客户端上传图像,将图像转换为不同的格式(在本例中为 .tif)并将其返回给客户端。
我遇到的问题是图像始终为 0kB。我似乎无法弄清楚问题所在。
View :
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype="multipart/form-data" }))
{
<input accept=".bmp, .gif, .jpg, .jpeg" name="file" type="file" />
<input type="submit" value="Submit" />
}
Controller Action :
[HttpPost]
[ActionName("Index")]
public ActionResult UploadImages(HttpPostedFileBase file)
{
var tiffEncoder = ImageCodecInfo.GetImageEncoders()
.SingleOrDefault(dec => dec.FormatID == ImageFormat.Tiff.Guid);
Stream imgStream = new MemoryStream();
using (EncoderParameters encParams = new EncoderParameters(1))
using (Image img = Image.FromStream(file.InputStream, true, true))
{
encParams.Param[0] = new EncoderParameter(Encoder.Quality, 100);
img.Save(imgStream, tiffEncoder, encParams);
}
var result = File(imgStream, "image/tiff", "image.tif");
return result;
}
经过调试,我清楚地看到 FileStream 属性包含数据。
imgStream
写入后需要倒带。在将其传递到 File
之前设置
imgStream.Position = 0;
我是一名优秀的程序员,十分优秀!