使用asp.net mvc3剃刀上传单个文件并使用jquery进行验证的最佳方式是什么?
我只需要用户上传jpg,png小于5mb。
谢谢
发布于 2012-05-11 05:44:57
除了jQuery验证(非常好的Acid的回答),你还应该做服务器验证。下面是一些简单的例子:
视图:
@if (TempData["imageUploadFailure"] != null)
{
@* Here some jQuery popup for example *@
}
@using (Html.BeginForm("ImageUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<legend>Add Image</legend>
<label>Image</label>
<input name="image" type="file" value=""/>
<br/>
<input type="submit" value="Send"/>
}控制器:
public ActionResult ImageUpload()
{
return View();
}
[HttpPost]
public ActionResult ImageUpload(HttpPostedFileBase image)
{
var result = ImageUtility.SaveImage("/Content/Images/", 1000000, "jpg,png", image, HttpContext.Server);
if (!result.Success)
{
var builder = new StringBuilder();
result.Errors.ForEach(e => builder.AppendLine(e));
TempData.Add("imageUploadFailure", builder.ToString());
}
return RedirectToAction("ImageUpload");
}ImageUtility帮助器类:
public static class ImageUtility
{
public static SaveImageResult SaveImage(string path, int maxSize, string allowedExtensions, HttpPostedFileBase image, HttpServerUtilityBase server)
{
var result = new SaveImageResult { Success = false };
if (image == null || image.ContentLength == 0)
{
result.Errors.Add("There was problem with sending image.");
return result;
}
// Check image size
if (image.ContentLength > maxSize)
result.Errors.Add("Image is too big.");
// Check image extension
var extension = Path.GetExtension(image.FileName).Substring(1).ToLower();
if (!allowedExtensions.Contains(extension))
result.Errors.Add(string.Format("'{0}' format is not allowed.", extension));
// If there are no errors save image
if (!result.Errors.Any())
{
// Generate unique name for safety reasons
var newName = Guid.NewGuid().ToString("N") + "." + extension;
var serverPath = server.MapPath("~" + path + newName);
image.SaveAs(serverPath);
result.Success = true;
}
return result;
}
}
public class SaveImageResult
{
public bool Success { get; set; }
public List<string> Errors { get; set; }
public SaveImageResult()
{
Errors = new List<string>();
}
}您也可以修补响应格式,不同的文件重命名或添加多个文件处理等功能。
https://stackoverflow.com/questions/10540901
复制相似问题