ASP.NET MVC 3 Razor文件上传

3

如何使用asp.net mvc3 razor上传单个文件并使用jquery进行验证是最佳方法。

我只需要上传小于5 mb的jpg、png文件。

谢谢。

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上传控件的Razor视图中使用。您也可以在标准上传输入中使用,只需在选择或提交之前触发此事件即可。

谢谢,我过去一年一直在使用这段代码,它非常好用。 - CD Smith
谢谢,但我还有一个问题,我如何调用onSelect()函数?像这样:<input type="file" name="file" id="file_uploader" onselect="OnSelect()" /> - Irakli Lekishvili
1
尝试使用 onchange 事件 onchange = onSelect(this); - CD Smith
@AlfalfaStrange 我已经在 Razor 页面上使用标准的 <input type="file"> 控件尝试了你的代码。当选择文件时,我通过 onchange 触发 onSelect 函数,但是它在第一行失败了。我得到的错误是 "e.files is undefined"。有什么想法吗? - Ciarán Bruen

5
除了jQuery验证(非常好的Acid的回答)之外,您还应该进行服务器验证。 这里是一个简单的示例:
VIEW:
@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>();
    }
}

您还可以调整响应格式,更改文件命名方式,为多文件处理添加功能等。


2

这仅用于指定要接受的文件类型:MSvisualstudio2010。

在您的View(.cshtml)中:

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

只需指定所需格式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接