2009-09-23 3 views
2

ASP.NET MVC 애플리케이션 용 업로드 스크립트 작업 중입니다. 하나의 파일에서 작동하는 구현이 있지만 여러 업로드를 처리하기 위해이 파일을 확장하고 싶습니다.여러 파일에 대한 Ajax 업로드 스크립트, jQuery ASP.NET MVC

업로드보기 (그래 난은 자체 파일이 jQuery 코드를 이동됩니다) :

<script type="text/javascript"> 
    var fieldCount = 0; 
    function addField() { 
     var name = 'file' + fieldCount; 
     var row = 'row' + fieldCount; 
     var str = '<p id="' + row + '"><label for="' + name + '">File to upload: <input type="file" name="' + name + '" id="' + name + '" />(100MB max size) <a onclick="removeRow(\'#' + row +  '\'); return false;">[-]</a></label></p>'; 
     fieldCount++; 
     $("#fields").append(str); 
    }; 
    function removeRow(id) { 
     if ($("#fields").children().size() > 1) { 
      $(id).remove(); 
     } 
    }; 
    $(function() { 
     $("#ajaxUploadForm").ajaxForm({ 
      iframe: true, 
      dataType: "json", 
      beforeSubmit: function() { 
       $("#resultBox").show(); 
       $("#status").html('<h1><img src="/Content/busy.gif" /> Uploading file...</h1>'); 
      }, 
      success: function(result) { 
       $("#ajaxUploadForm").unblock(); 
       $("#ajaxUploadForm").resetForm(); 
       var tcolor; 
       var msg; 
       if (!result.message) { 
        tcolor = "red"; 
        msg = result.error; 
       } 
       else { 
        tcolor = "green"; 
        msg = result.message; 
       } 
       $("#resultBox").show(); 
       $("#status").html('<span style="color:' + tcolor + ';">' + msg + '</span>').animate({ opacity: 1.0 }, 3000).fadeOut('slow', function() { 
        $("#resultBox").hide(); 
       }); 
      }, 
      error: function(xhr, textStatus, errorThrown) { 
       $("#ajaxUploadForm").unblock(); 
       $("#ajaxUploadForm").resetForm(); 
       $("#resultBox").add("p").attr("id", "status").css("margin-top", "15px").css("padding", "20px"); 
       $("#status").html('<span style="color:red;">Error uploading file</span>').animate({ opacity: 1.0 }, 3000).fadeOut('slow', function() { 
        $("#resultBox").hide(); 
       }); 
      } 
     }); 
    }); 
</script> 
<form id="ajaxUploadForm" action="<%= Url.Action("AjaxUpload", "Upload")%>" method="post" enctype="multipart/form-data"> 
    <fieldset id="uploadFields"> 
     <legend>Upload a file</legend> 
     <div id="fields"></div> 
     <input id="ajaxUploadButton" type="submit" value="Submit" />    
    </fieldset> 
    <a onclick="addField(); return false;" id="add">Add</a> 
    <div id="resultBox"> 
     <p id="status" style="margin:10px;"></p> 
    </div> 
</form> 

조치 결과 : 내가 얻을 개념을 from this blog post를 사용

public FileUploadJsonResult AjaxUpload(HttpPostedFileBase file) 
{ 
    Upload fileToUpload; 
    try 
    { 
     fileToUpload = new Upload 
     { 
      filename = file.FileName, 
      filesize = file.ContentLength, 
      date = DateTime.Now, 
      id = Guid.NewGuid() 
     }; 

    var savedFileName = Server.MapPath(Path.Combine(@"~/uploads", Path.GetFileName(fileToUpload.filename))); 
    if (System.IO.File.Exists(savedFileName)) 
    { 
     throw new Exception(string.Format("The file '{0}' already exists on the server.", file.FileName)); 
    } 
    file.SaveAs(savedFileName); 
    } 
    catch (Exception ex) 
    { 
     return new FileUploadJsonResult { Data = new { error = string.Format("Upload failure: {0}", ex.Message), message = string.Empty } }; 
    } 
    return new FileUploadJsonResult { Data = new { message = string.Format("{0} uploaded successfully. (id:{1})", Path.GetFileName(file.FileName), fileToUpload.id) } }; 
} 

여기에 원래의 구현은 이 모든 것이 굴러.


지금 추가 내 자바 스크립트로/필드를 제거, 나는 약간 조치 결과를 변경 :

public List<FileUploadJsonResult> AjaxUpload(HttpPostedFileBase fileBase) 
{ 
    var results = new List<FileUploadJsonResult>(); 
    try 
    { 
     if (Request.Files.Count > 0) 
     { 
      Upload uploadFile; 
      for (var i = 0; i <= (Request.Files.Count - 1); i++) 
      { 
       HttpPostedFileBase file = Request.Files[i]; 
       uploadFile = new Upload 
       { 
        filename = file.FileName, 
        filesize = file.ContentLength, 
        date = DateTime.Now, 
        id = Guid.NewGuid() 
       }; 
       var savedFileName = Server.MapPath(Path.Combine(@"~/uploads", Path.GetFileName(uploadFile.filename))); 
       if (System.IO.File.Exists(savedFileName)) 
       { 
        results.Add(new FileUploadJsonResult { Data = new { error = string.Format("Upload failure: {0}", string.Format("The file '{0}' already exists on the server.", file.FileName)), message = string.Empty } }); 
       } 
       file.SaveAs(savedFileName); 
       results.Add(new FileUploadJsonResult { Data = new { message = string.Format("{0} uploaded successfully", file.FileName) } }); 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     results.Add(new FileUploadJsonResult { Data = new { error = string.Format("Upload failure: {0}", ex.Message), message = string.Empty } }); 
    } 
    return results; 
} 

나는 종류의이 시점에서 막혔어요. 업로드가 정상적으로 작동하지만 단일 항목이 아닌 목록을 반환하기 때문에 자바 스크립트 오류가 발생합니다. 결과 목록을 반복하기 위해 코드의 일부분을 조정하면 상상할 수 있습니다.

내가 할 수 있기를 바랄 또 다른 점은 각 파일 업로드가 완료된 후에 resultBox에 성공 텍스트를 추가하는 것입니다.

도움이 될 것입니다. 감사!

답변

0

여기에 ActionResult를 반환해야합니다. 목록을 반환 할 수 없습니다. 또한 Request.Files 컬렉션을 사용하므로 HttpPostedFileBase fileBase를 작업에 사용할 필요가 없습니다. 이 같은

뭔가 당신이 HttpModule to provide a progress bar의 예는 I가 장소에있는 jQuery.form 플러그인과 스크립트에 대한 JQuery와 UI를 진행 표시 줄

+0

를 사용 할 수 있습니다, 또한 당신에게

public FileUploadJsonResult AjaxUpload() { try { foreach (string name in Request.Files) { var file = Request.Files[name]; if (!string.IsNullOrEmpty(file.FileName)) { file.SaveAs(Server.MapPath(Path.Combine(@"~/uploads", Path.GetFileName(file.FileName))); } } } catch (Exception ex) { return new FileUploadJsonResult { Data = new { error = string.Format("Upload failure: {0}", ex.Message), message = string.Empty } }; } return new FileUploadJsonResult { Data = new { message = "file(s) uploaded successfully" } }; } 

을 할 수 제대로 작동하려면 HttpPostedFileBase를 인수로 가져야합니다. 원래 구현에서는 인수가 코드에서 사용되는 것을 볼 수 있습니다. 다중 파일 구현에서는 대신 각 파일을 처리 할 수 ​​있도록 Request.Files를 사용합니다. – Anders

+0

안녕하세요 Anders, 원본 구현에서 사용되지만 다중 파일 구현에서는 사용되지 않습니다. js를 변경하여 각 파일을 별도로로드하고 원래 구현을 사용할 수 있습니다 ...? –

+0

나는 당신이 제안한 것을하는 것에 대해 어떻게 생각하는지 완전히 모른다. 지금까지 말했듯이 자바 스크립트는 양식을 제출하고 숨겨진 iframe에 양식 데이터를 덤프하여 양식을 비동기 적으로 제출할 수 있습니다. 나는 js와 녹슨 친절하고 나는 단지 물건의 스윙에 다시 시작합니다. 어떤 제안이나 시도해 볼 수 있습니까? 감사! – Anders