在调整图像大小后 MVC 后存储图像时找不到路径的一部分
本文关键字:图像 找不到 路径 一部分 MVC 调整 存储 | 更新日期: 2023-09-27 18:33:17
上传到文件夹后,我正在调整图像大小。我以这种格式将路径存储在数据库中/内容/上传//e1f1d755-2b6c-4ec0-8b5e-0a5fa569292c.Img0001.jpg但是在调整图像大小时,我给出了相同的路径,我将其保存在可变路径中。但它以这种形式出现 C:''Content''Uploads''e1f1d755-2b6c-4ec0-8b5e-0a5fa569292c。Img0001.jpg导致保存调整大小的图像时出错。找不到路径的一部分C:''Content''Uploads''e1f1d755-2b6c-4ec0-8b5e-0a5fa569292c.Img0001.jpg这是我的代码:
[HttpPost]
public ActionResult UploadPic(FileManagement fmanage, HttpPostedFileBase file)
{
var path = String.Empty;
var directory = "/Content/Uploads/";
if (file != null && file.ContentLength > 0)
{
String FileExtn = System.IO.Path.GetExtension(file.FileName).ToLower();
if (!(FileExtn == ".jpg" || FileExtn == ".png" || FileExtn == ".gif"))
{
ViewBag.error = "Only jpg, gif and png files are allowed!";
}
else
{
var fileName = string.Format("{0}.{1}", Guid.NewGuid(), Path.GetFileName(file.FileName));
path = Path.Combine(directory + "/", fileName);
file.SaveAs(Server.MapPath(path));
using (var input = new Bitmap(file.InputStream))
{
int width;
int height;
if (input.Width > input.Height)
{
width = 128;
height = 128 * input.Height / input.Width;
} //if
else
{
height = 128;
width = 128 * input.Width / input.Height;
} //else
using (var thumb = new Bitmap(width, height))
using (var graphic = Graphics.FromImage(thumb))
{
graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
graphic.DrawImage(input, 0, 0, width, height);
using (var output = System.IO.File.Create(path))
{
thumb.Save(output, System.Drawing.Imaging.ImageFormat.Jpeg);
} //using
} //using
}
}
如何在存储调整大小的图像时具有相同的路径。提前感谢您的帮助。
请尝试以下操作:
而不是:
var directory = "/Content/Uploads/";
这样做:
var directory = "~/Content/Uploads/";
然后替换:
path = Path.Combine(directory + "/", fileName);
跟:
path = Path.Combine(Server.MapPath(directory), fileName);