上传图像,保存到数据库,在视图中创建缩略图和显示

时间:2014-03-22 12:41:48

标签: c# asp.net-mvc

我正在构建一个图像库,主要用于学习ASP.Net MVC。经过数小时的谷歌搜索和堆栈溢出,我终于完成了上传图像,保存到数据库,创建缩略图和在视图中显示的目标。下面显示的代码至少是臃肿的,我正在寻找关于如何改进它的任何建议。

以下是查看表单输入

<div class="form-group">
@Html.LabelFor(model => model.ImageData, new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input name="Image" type="file" />
@Html.ValidationMessageFor(model => model.ImageData)
</div>
</div>

以下是Controller中的Create Action

public ActionResult Create(ArtWork artwork, HttpPostedFileBase image)
        {
           if (ModelState.IsValid)
            {
                if (image != null)
                {
                    //attach the uploaded image to the object before saving to Database
                    artwork.ImageMimeType = image.ContentLength;
                    artwork.ImageData = new byte[image.ContentLength];
                    image.InputStream.Read(artwork.ImageData, 0, image.ContentLength);

                    //Save image to file
                    var filename = image.FileName;
                    var filePathOriginal = Server.MapPath("/Content/Uploads/Originals");
                    var filePathThumbnail = Server.MapPath("/Content/Uploads/Thumbnails");
                    string savedFileName = Path.Combine(filePathOriginal, filename);
                    image.SaveAs(savedFileName);

                    //Read image back from file and create thumbnail from it
                    var imageFile = Path.Combine(Server.MapPath("~/Content/Uploads/Originals"), filename);
                    using (var srcImage = Image.FromFile(imageFile))
                    using (var newImage = new Bitmap(100, 100))
                    using (var graphics = Graphics.FromImage(newImage))
                    using (var stream = new MemoryStream())
                    {
                        graphics.SmoothingMode = SmoothingMode.AntiAlias;
                        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        graphics.DrawImage(srcImage, new Rectangle(0, 0, 100, 100));
                        newImage.Save(stream, ImageFormat.Png);
                        var thumbNew = File(stream.ToArray(), "image/png");
                        artwork.ArtworkThumbnail = thumbNew.FileContents;
                    }                
                }

               //Save model object to database
                db.ArtWorks.Add(artwork);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(artwork);
        }

这是一个从数据库中获取缩略图的Action方法

public FileContentResult GetThumbnailImage(int artworkId)
        {
            ArtWork art = db.ArtWorks.FirstOrDefault(p => p.ArtWorkId == artworkId);
            if (art != null)
            {
                return File(art.ArtworkThumbnail, art.ImageMimeType.ToString());
            }
            else
            {
                return null;
            }
        }

最后在这里的视图中显示,

<td>
            <img src="@Url.Action("GetThumbnailImage", "Artwork", new { Model.ArtWorkId })" alt="Artwork Image" />
        </td>

就像我说的,这很有效,但我相信使用ASP.Net和Entity Framework可以更好地上传,保存和检索数据库中的图像。

0 个答案:

没有答案