调整大小后,在存储图像时找不到路径的一部分mvc

时间:2013-09-29 16:10:07

标签: c# asp.net-mvc image

我在上传到文件夹后调整图像大小。我已经以这种格式在db中存储了路径 /Content/Uploads//e1f1d755-2b6c-4ec0-8b5e-0a5fa569292c.Img0001.jpg 但是在调整图像大小时我没有给出相同的路径,我将它保存在一个可变路径中。但它出现在这种形式C:\ Content \ Uploads \ e1f1d755-2b6c-4ec0-8b5e-0a5fa569292c.Img0001.jpg导致错误在保存调整大小的image.cannot找到路径的一部分 C:\内容\上传\ 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

                }
          }

如何在存储已调整大小的图像时使用相同的路径。请提前获取帮助。

1 个答案:

答案 0 :(得分:0)

请尝试以下方法:

而不是:

 var directory = "/Content/Uploads/";

这样做:

 var directory = "~/Content/Uploads/";

然后替换:

path = Path.Combine(directory + "/", fileName);

使用:

path = Path.Combine(Server.MapPath(directory), fileName);