我已经使用ASP.NET Mvc 3和Microsoft.Web.Helpers NuGet包实现了图像的文件上传.实现是简单的,因为它允许您浏览文件并将其上传到指定的目录.
这是我使用ASP.NET MVC 3和Microsoft.Web.Helpers NuGet插件的图像上传解决方案.
namespace MvcImageUpload.Models { public class ImageUploadviewmodel { [UIHint("UploadedImage")] public string ImageUrl { get; set; } public string ImageAltText { get; set; } } }
现在对于控制器,我简单地把它放到了家庭控制器中,因为这只是一个模拟项目来使它工作.我刚刚添加了一个ActionResult,它将ImageUploadviewmodel作为参数.
public ActionResult Upload(ImageUploadviewmodel model) { var image = WebImage.GetImageFromRequest(); if (image != null) { if (image.Width > 500) { image.Resize(500,((500 * image.Height) / image.Width)); } var filename = Path.GetFileName(image.FileName); image.Save(Path.Combine("../Uploads/Images",filename)); filename = Path.Combine("~/Uploads/Images",filename); model.ImageUrl = Url.Content(filename); model.ImageAltText = image.FileName.Substring(0,image.FileName.Length - 4); } return View("Index",model); }
我对于上传图像的看法很简单,它有一个Html.BeginForm,它处理Post Form方法,并且将编码类型设置为“multipart / form-data”.
然后使用Microsoft.Web.Helpers.FileUpload帮助器,我从HTTP发布请求一个图像,然后使用名为ImageViewer的自定义DisplayFor模板显示它.
@model MvcImageUpload.Models.ImageUploadviewmodel @using Microsoft.Web.Helpers; @{ ViewBag.Title = "Index"; } <h2>Image Uploader</h2> @using (Html.BeginForm("Upload","Home",FormMethod.Post,new { @encType = "multipart/form-data" })) { @FileUpload.GetHtml(initialNumberOfFiles: 1,allowMoreFilesToBeAdded: false,includeFormTag: false,addText: "Add Files",uploadText: "Upload File") <br /> <input type="submit" name="submit" value="Upload Image" text="Upload Images" style="font-size: .9em;" /> @Html.DisplayFor(x => x,"ImageViewer")<br /> }
这是自定义DisplayTemplate的外观
@model MvcImageUpload.Models.ImageUploadviewmodel @if (Model != null) { <h4 style="color:Green;">Upload Success!</h4> <p> Alt Text has been set to <strong>@Model.ImageAltText</strong> </p> <img style="padding: 20px;" src="@(String.IsNullOrEmpty(Model.ImageUrl) ? "" : Model.ImageUrl)" id="uploadedImage" alt="@Model.ImageAltText"/> }
这一切工作,图像成功上传到表单上的/Uploads/Images/FileName.extension.
我的问题
我现在可以有另一个视图显示该目录中的所有图像,分页并能够从视图和目录中选择和删除和映像?
另外我知道Microsoft.Web.Helpers.FileUpload,支持上传多个文件,但是我找不到如何用我目前的解决方案来实现.任何帮助都会被大大的赞赏.
解决方法
单击“上传图像”按钮后,系统应调用使用“请求”获取文件的方法.
[HttpPost] public ActionResult Upload() { if(Request.Files != null && Request.Files.Count > 0) { for (int i = 0; i < request.Files.Count; i++) { var postFile = request.Files[i]; if (postFile != null && postFile.ContentLength > 0) { if (postFile.ContentLength < GetMaxRequestLength()) //10MB { var file = new ContractAttachment { Name = Path.GetFileName(postFile.FileName),ContentType = postFile.ContentType,FileLength = postFile.ContentLength,FileData = GetStreamBuffer(postFile) }; files.Add(file); } } } } }
希望这个帮助.