所以我有一个处理文件上传的动作。我做的是检查文件大小是否为100kb,如果不是,我将其调整到一定的宽度和高度(虽然我不确定是否正确的方式达到所需的大小,想法?)
然后我打算将它保存到我网站的子域中。
这就是行动的样子
public ActionResult New(string account, int id, HttpPostedFileBase file)
{
if (file == null)
{
ModelState.AddModelError("", "File not found.");
return View();
}
if (!ImageUpload.FileTypeValid(file.ContentType))
{
ModelState.AddModelError("", "File type is invalid. Please choose a different file.");
return View();
}
if (file.ContentLength > 100)
{
Image image = ImageUpload.ResizeFile(file, 100, 100);
}
try
{
icdb.SaveChanges();
ModelState.AddModelError("", "Sucesfully saved Image.");
return RedirectToAction("Details", "OfAController", new { account = account, id= id});
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
return View();
}
这是调整大小的方法
static public Image ResizeFile(HttpPostedFileBase file, int targeWidth, int targetHeight)
{
Image originalImage = Image.FromStream(file.InputStream, true, true);
var newImage = new MemoryStream();
Rectangle origRect = new Rectangle(0, 0, originalImage.Width, originalImage.Height);
// if targets are null, require scale. for specified sized images eg. Event Image, or Profile photos.
int newWidth = targeWidth;
int newHeight = targetHeight;
var bitmap = new Bitmap(newWidth, newHeight);
try
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(originalImage, new Rectangle(0, 0, newWidth, newHeight), origRect, GraphicsUnit.Pixel);
bitmap.Save(newImage, originalImage.RawFormat);
}
return (Image)bitmap;
}
catch
{ // error before IDisposable ownership transfer
if (bitmap != null)
bitmap.Dispose();
throw new Exception("Error resizing file.");
}
}
所以我的问题是,我试图找到如何将此调整大小的文件保存到我的目录的方法。然后我一直发现在调整大小之前我必须先上传图像?是对的吗?或者有没有办法在我保存到目录之前可以调整大小?
思想?
谢谢!