3

これは、asp.net mvc3 razorを使用して単一のファイルをアップロードし、jqueryを使用して検証するための最良の方法です。

ユーザーがアップロードする必要があるのは、5MB未満のjpg、pngのみです。

ありがとう

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 に答える