programing

ASP에서 HTML5 다중 파일 업로드를 어떻게 처리합니까?NET MVC?

mailnote 2023. 8. 29. 20:49
반응형

ASP에서 HTML5 다중 파일 업로드를 어떻게 처리합니까?NET MVC?

새로운 HTML5 FormData API를 사용하여 AJAX/Jquery를 통해 파일을 업로드하는 방법에 대한 설명과 함께 다음과 같은 훌륭한 스레드를 찾았습니다.

다음은 최신 JQuery 1.8+ 구문으로 약간 업데이트된 코드 버전입니다.

$(':button').click(function(){
    var formData = new FormData($('form')[0]);
    $.ajax({
        url: '/Upload',  //my ASP.NET MVC method
        type: 'POST',
        // handle the progress report
        xhr: function() {  // Custom XMLHttpRequest
            var myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){ // Check if upload property exists
                myXhr.upload.addEventListener('progress',progressHandlingFunction,    false); // For handling the progress of the upload
            }
            return myXhr;
        },

        // Form data
        data: formData,

        //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
    })
    .done(function(){
        alert("success");
    })
    .fail(function(){
        alert("error");
    });
});

function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('progress').attr({value:e.loaded,max:e.total});
    }
}

그리고 여기 양식이 있습니다.

<form enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />
</form>
<progress></progress>

서버 쪽에는 이런 것이 있습니다.

[HttpPost]
public string Upload(HttpPostedFileBase file)
{
    // do something with file
    return "you uploaded a file called " + file.FileName;
}

이것은 아주 잘 작동합니다.파일 대화 상자에서 "다중" 특성을 사용하고 여러 파일을 보내기 전까지.

<form enctype="multipart/form-data">
    <input name="file" type="file" multiple="multiple" />
    <input type="button" value="Upload" />
</form>
<progress></progress>

다음 솔루션을 제안하는 다양한 페이지를 온라인에서 찾을 수 있습니다.

public string Upload(IEnumerable<HttpPostedFileBase> files)
{
    foreach(var file in files)
         ...
}

이런. 작동하지 않습니다.

public string Upload(List<HttpPostedFileBase> files)
{
    foreach(var file in files)
         ...
}

아니요, 작동하지 않아요

public string Upload(IEnumerable files)
{
    foreach(var file in files)
         ...
}

컴파일도 안 됩니다.

public string Upload(HttpPostedFileBase[] files)
{
    foreach(HttpPostedFileBase file in files)
         ...
}

그거 알아?작동하지 않습니다.요청을 처리해 보겠습니다.파일 대신에.신뢰할 수 있는 오래된 요청입니다.파일입니다. 절대 실패하지 않습니다.

public string Upload()
{
    foreach (HttpPostedFileBase uf in Request.Files)
         ...
}

스포일러 경고:동작되지 않습니다.

아하. 알겠습니다!Request에서 키를 반복해 보겠습니다.파일 대신에.

public string Upload()
{
    foreach(var key in Request.Files.AllKeys)
    {
        var file = Request.Files[key];
    }
}

다시 말하지만, 그것은 작동하지 않습니다.

항상 신뢰할 수 있고 역동적인 머리를 가진 Rick Strahl의 블로그에서 다음과 같이 작동하는 것은 무엇입니까?

public string Upload()
{
    for (int i = 0; i < Request.Files.Count; i++)
    {
        var file = Request.Files[i];
    } 
}

그 이유는 다음으로 전달된 파일 모음 때문입니다.Request.Files 단일 파일 업로드 대화 상자에서 나왔기 때문에 모두 같은 이름을 가집니다.

서버측 메소드는 파일을 포함하는 단일 개체를 전달하며 어떤 이유에서인지 요청합니다.파일만이 그것을 얻을 수 있는 유일한 방법입니다.

제가 이것을 추가함으로써 누군가의 두통을 조금이라도 덜어줬기를 바랍니다.

제 경우에는 View Model 필드에 모든 파일을 바인딩하는 것이 효과적이었습니다.View Model은 제가 프런트 엔드에 사용하는 모델입니다.

@using School.ViewModels
@model UserProfileViewModel


<form enctype="multipart/form-data">
<input id="username"name="username" type="text" />
<input name="Myfiles" type="file" multiple="multiple" />
<input type="button" value="Upload" />
</form>

UserProfileViewModel.cs

namespace School.ViewModels
{
    public class UserProfileViewModel
    {
        public long Username { get; set; }

        public List<HttpPostedFileBase> Myfiles { get; set; }
    }
}

UserProfilePicturesController.cs

public ActionResult Create([Bind(Include="Username,Myfilese")] UserprofileViewModel userprofileViewModel)
{
     var files = userprofileViewModel.Myfiles;
     foreach(HttpPostedFileBase file in files)
     {
         //do something here
     }
}

언급URL : https://stackoverflow.com/questions/21784647/how-do-i-handle-html5-multiple-file-uploads-in-asp-net-mvc

반응형