2014-05-12 2 views
0

양식에서 파일을 받고 각 파일의 정보를 반환하는 방법을 개발했습니다. 아마 비슷한 것을하는 인터넷에 하나가 있을지 모르지만 나는 찾지 못했다. 그러나 나는 여전히 C#을 배우고 있으며 나는 나를 도울 방법을 만들고 싶어한다.ASP.NET MVC로 여러 파일 업로드

나는 2 장으로 게시하고 싶습니다. 하나는 확인을하고 다른 이유는 코드를 공유하는 것입니다.

의견이 있습니까?

마음에 드시면! 그것을 사용하십시오 :)

나는 전체 코드를 주석을 달 시간이 없었습니다. :(

방법

 public String[,] upload(IEnumerable<HttpPostedFileBase> _files, List<string> _flSupportedTypes,int _flSizeLimit, string _serverPath) 
     { 
      /* 
      * Array Details 
      * 
      * { Fields detail } 
      * [1~] [0] - Status code 
      *  [1] - Status message 
      *  [2] - Upload file Name 
      *  [3] - New file name 
      *  [4] - Virtual Path 
      *  [5] - Local Path 
      *  
      * { General details } 
      * [0] [0] - Status Code 
      *  [1] - Status message 
      *  [2] - total fields 
      *  [3] - total fields processed 
      */ 
      int totalFieldsUpload = _files != null ? _files.Count() : 0; 
      int countFieldsUpload = 0; 
      int countFilesUpload = 0; 
      String[,] filesResult = new String[totalFieldsUpload + 1, 6]; 

      if(totalFieldsUpload == 0) 
      { 
       filesResult[0, 0] = "0"; 
       filesResult[0, 1] = "No fields"; 
       filesResult[0, 2] = "0"; 
       filesResult[0, 3] = "0"; 
      } 
      else 
      { 
       filesResult[0, 0] = "1"; 
       filesResult[0, 1] = "OK"; 
       filesResult[0, 2] = totalFieldsUpload.ToString(); 

       if (!Directory.Exists(_serverPath)) 
        Directory.CreateDirectory(_serverPath); 

       foreach (var file in _files) 
       { 
        bool isContentOK = false; 
        countFieldsUpload++; 

        if (file != null) 
        { 
         String newfileName = DateTime.Now.ToFileTimeUtc() + 
               "_" + Path.GetRandomFileName() + 
               "." + file.FileName.ToString().Split('.').Last(); 

         String localPath = _serverPath + newfileName; 
         String virtualPath = localPath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], "~/").Replace(@"\", "/"); 

         if (file.ContentLength <= _flSizeLimit) 
         { 
          foreach (var type in _flSupportedTypes) 
          { 
           if (file.ContentType == type) 
           { 
            file.SaveAs(localPath); 
            isContentOK = true; 

            countFilesUpload++; 

            break; 
           } 
           else 
            isContentOK = false; 

          } 

          filesResult[countFieldsUpload, 0] = "1"; 
          filesResult[countFieldsUpload, 1] = isContentOK ? "OK" : "ContentType Failed"; 
          filesResult[countFieldsUpload, 2] = file.FileName; 
          filesResult[countFieldsUpload, 3] = newfileName; 
          filesResult[countFieldsUpload, 4] = virtualPath; 
          filesResult[countFieldsUpload, 5] = localPath; 
         } 
         else 
         { 
          filesResult[countFieldsUpload, 0] = "0"; 
          filesResult[countFieldsUpload, 1] = "Size Failed"; 
          filesResult[countFieldsUpload, 2] = file.FileName; 
         } 

        } 
        else 
        { 
         filesResult[countFieldsUpload, 0] = "0"; 
         filesResult[countFieldsUpload, 1] = "Field empty"; 
        } 
       } 

       filesResult[0, 3] = countFilesUpload.ToString(); 
      } 

      return filesResult;    
     } 

HTML

@using (Html.BeginForm("ActionTest", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    @Html.AntiForgeryToken() 
    Html.EnableClientValidation(false); 
    <div class="form-group"> 
     <label for="photo">Photo:</label> 
     <input type="file" name="photo[0]" id="photo_0"> 
     <input type="file" name="photo[1]" id="photo_1"> 
     <input type="file" name="photo[2]" id="photo_2"> 
     <input type="submit" /> 
    </div> 
} 

액션 결과가

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult ActionTest(IEnumerable<HttpPostedFileBase> photo) 
{ 
    List<string> supportedTypes = new List<string>() { "image/jpeg", "image/gif", "image/png" }; 
    String   serverPath  = Server.MapPath("/") + ConfigurationManager.AppSettings["imgTmpUploadPath"].ToString(); 
    String[,]  filesResult  = upload(photo, supportedTypes, 1048576, serverPath); 

    return View(); 
} 

답변

1

당신은에서 읽을 수 있습니다오브젝트는 다음과 같습니다 :

[HttpPost] 
    public ActionResult Page2(FormCollection objCollection) 
    { 
     foreach (string fileName in Request.Files) 
     { 

     HttpPostedFileBase file = Request.Files[fileName]; 

     ... 
     } 
    } 
+0

고마워요! :) 나는 그것에 대해 연구 할 것이다. – Canela