asp.net的MVC 3剃须刀文件上传(asp.net mvc 3 razor file uplo

2019-06-24 07:47发布

这是上传与asp.net MVC3剃刀单个文件,并与jQuery验证最佳途径。

我只需要用户上传JPG,PNG小于5 MB。

谢谢

Answer 1:

您需要使用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的上传控件剃刀视图中使用此。 您可以使用标准上传输入使用,以及,刚刚火上选择或提交之前,此事件



Answer 2:

除了jQuery验证(非常漂亮酸的回答)你也应该做的服务器验证。 下面是一些简单的例子:

视图:

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

你也可以与响应格式,不同的文件重命名或添加功能支持多种文件处理等鼓捣



Answer 3:

这仅仅是指定的文件类型被接受:MSvisualstudio2010。

在视图(.cshtml):

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

只要指定你所需要的格式。



文章来源: asp.net mvc 3 razor file upload