为上载的图像创建缩略图

时间:2016-11-06 13:43:56

标签: c# asp.net-mvc thumbnails image-uploading

我有一个asp.net mvc应用程序,我可以一次上传多个图像,并且工作正常,但我有一个问题,从原件创建缩略图。

以下是代码:

[HttpPost]
        public ActionResult SaveUploadedFile()
        {
            bool isSavedSuccessfully = true;
            string fName = "";

            try
            {
                foreach (string fileName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[fileName];

                    fName = file.FileName;

                    if (file != null && file.ContentLength > 0)
                    {
                        var originalDirectory = new DirectoryInfo(string.Format("{0}Images", Server.MapPath(@"\")));

                        string pathString = Path.Combine(originalDirectory.ToString(), "Gallery");
                        string pathString2 = Path.Combine(originalDirectory.ToString(), "Gallery\\Thumbs");

                        //var fileName1 = Path.GetFileName(file.FileName);

                        bool exists = Directory.Exists(pathString);
                        bool exists2 = Directory.Exists(pathString2);

                        if (!exists)
                            Directory.CreateDirectory(pathString);

                        if (!exists2)
                            Directory.CreateDirectory(pathString2);

                        var path = string.Format("{0}\\{1}", pathString, file.FileName);

                        file.SaveAs(path);

                        //WebImage img = new WebImage(file.InputStream);
                        WebImage img = new WebImage(fileName);
                        //if (img.Width > 1000)
                        img.Resize(100, 100);
                        img.Save(pathString2);

                    }

                }

            }
            catch (Exception ex)
            {
                isSavedSuccessfully = false;
            }

            if (isSavedSuccessfully)
            {
                return Json(new { Message = fName });
            }
            else
            {
                return Json(new { Message = "Error in saving file" });
            }
        }

所以基本上file.SaveAs(path);是最后一行有效,我实际上保存了图像,但在那行之后我尝试创建并保存大拇指但它不起作用(我确实得到了Thumbs文件夹之前创建的。)

我也得到Error in saving file响应,但那是因为我正在尝试创建并保存大拇指,如果我删除它然后我没有得到它,我不知道如何返回实际的错误实际看到错误是什么。

1 个答案:

答案 0 :(得分:0)

答案是:

var path2 = string.Format("{0}\\{1}", pathString2, file.FileName)

WebImage img = new WebImage(file.InputStream);
img.Resize(250, 250);
img.Save(path2);