3

这是使用 asp.net mvc3 razor 上传单个文件并使用 jquery 验证的最佳方法。

我只需要用户上传 jpg,png 小于 5 mb。

谢谢

4

3 回答 3

8

您需要使用 javascript 进行验证,这是一个示例

function onSelect(e) {
    if (e.files[0].size > 256000) {
        alert('The file size is too large for upload');
        e.preventDefault();
        return false;
    }
    // Array with information about the uploaded files
    var files = e.files;
    var ext = $('#logo').val().split('.').pop().toLowerCase();
    if ($.inArray(ext, ['gif', 'jpeg', 'jpg', 'png', 'tif', 'pdf']) == -1) {
        alert('This type of file is restricted from being uploaded due to security reasons');
        e.preventDefault();
        return false;
    } 
    return true;
}

这表示文件不得大于 256K,并且只允许 gif、jpg、jpeg、tif、png 和 pdf。只需将 256000 更改为 5000000 和您的特定文件类型

我在 MVC 3 中使用 Telerik 上传控件在剃刀视图中使用它。您也可以使用标准上传输入,只需在选择时或提交之前触发此事件

于 2012-05-10T20:05:24.047 回答
5

除了 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>();
    }
}

您还可以修改响应格式、不同的文件重命名或为多个文件处理添加功能等。

于 2012-05-10T21:44:56.947 回答
2

这只是为了指定要接受的文件类型:MSvisualstudio2010。

在您的视图(.cshtml)中:

ATTACHMENT:<input type="file" name="file" id="file" accept=".PNG,.TXT,.JPG,.BMP" />

只需指定您需要的格式。

于 2012-09-10T09:02:13.553 回答