1

通过上传控件上传图像并将该图像转换为缩略图并将文件实际图像保存在图像文件夹中,并将缩略图图像保存在 asp.net-mvc3 中的缩略图图像文件夹中

4

1 回答 1

1

我使用名为Image Resizer的 3rd 方库。我在上传图像和保持质量方面遇到了困难,这个库帮助了我很多。

在您看来:

@model YourProject.ViewModels.ProductImageUploadCreateViewModel
@using (Html.BeginForm("Upload", "ProductImage", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
     <input type="file" name="ImageFile1" id="ImageFile1">
}

你的控制器:

public class ProductImageController : Controller
{
     [HttpPost]
     public ActionResult Upload(ProductImageUploadCreateViewModel viewModel)
     {
          if (!ModelState.IsValid)
          {
               return View(viewModel);
          }

          if (viewModel.ImageFile1 != null)
          {
               UploadImage(viewModel.ProductId, "1", viewModel.ImageFile1);
          }

          // Return to where ever...
     }
}

您的上传方式:

private void UploadImage(int productId, string imageNo, HttpPostedFileBase imageFile)
{
     string uploadPath = Server.MapPath("~/Assets/Images/Products/" + productId);
     if (!Directory.Exists(uploadPath))
     {
          Directory.CreateDirectory(uploadPath);
     }

     Dictionary<string, string> versions = new Dictionary<string, string>();
     versions.Add("_m", "width=150&height=150&scale=both&format=jpg");  // Medium size

     string filePrefix = productId + "_" + imageNo;
     versions.Add("_s", "width=90&height=90&scale=both&format=jpg");  // Small size
     versions.Add("_l", "width=300&height=300&scale=both&format=jpg");  // Large size

     foreach (string fileSuffix in versions.Keys)
     {
          // Generate a filename
          string fileName = Path.Combine(uploadPath, filePrefix + fileSuffix);

          // Let the image builder add the correct extension based on the output file type
          fileName = ImageBuilder.Current.Build(imageFile, fileName, new ResizeSettings(versions[fileSuffix]), false, true);
     }
}

看看他们的网站,有几个示例可供您使用。我希望这有帮助 :)

于 2012-05-11T12:26:52.977 回答