2010-08-11 6 views
1

양식을 통해 파일을 업로드 한 다음 SQL에 BLOB 형식으로 저장하려고합니다.ASP MVC 2 (blob) 데이터베이스에 파일 업로드

난 이미 내 데이터베이스가 완전히 덩어리를 취할 수 있으며, 나는 로컬 디렉토리에 저장, 파일을 컨트롤러를 가지고 내 양식이 잘 작동이 모든 내가 놓친 거지 이제

[AcceptVerbs(HttpVerbs.Post)] 
     public ActionResult FileUpload(int id, HttpPostedFileBase uploadFile) 
     { 

      //allowed types 
      string typesNonFormatted = "text/plain,application/msword,application/pdf,image/jpeg,image/png,image/gif"; 
      string[] types = typesNonFormatted.Split(','); 

      // 
      //Starting security check 

      //checking file size 
      if (uploadFile.ContentLength == 0 && uploadFile.ContentLength > 10000000) 
       ViewData["StatusMsg"] = "Could not upload: File too big (max size 10mb) or error while transfering the file."; 

      //checking file type 
      else if(types.Contains(uploadFile.ContentType) == false) 
       ViewData["StatusMsg"] = "Could not upload: Illigal file type!<br/> Allowed types: images, Ms Word documents, PDF, plain text files."; 

      //Passed all security checks 
      else 
      { 
       string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"), 
               Path.GetFileName(uploadFile.FileName)); //generating path 
       uploadFile.SaveAs(filePath); //saving file to final destination 

       ViewData["StatusMsg"] = "Uploaded: " + uploadFile.FileName + " (" + Convert.ToDecimal(uploadFile.ContentLength)/1000 + " kb)"; 

       //saving file to database 
       // 
       //MISSING 
      } 

      return View("FileUpload", null); 
     } 

파일을 데이터베이스에 저장 중입니다. 주제에 대해 아무 것도 찾을 수 없었습니다 ... 정규 웹 사이트에서는 할 수있는 방법을 찾았지만 MVC2에서는 찾지 못했습니다.

모든 종류의 도움을 환영합니다!

감사합니다.

답변

5

이 도움이 될 수 : http://byatool.com/mvc/asp-net-mvc-upload-image-to-database-and-show-image-dynamically-using-a-view/

을 당신이 당신의 컨트롤러 방법에 HttpPostedFileBase을 가지고 있기 때문에, 당신이 할 필요가있다 :

int length = uploadFile.ContentLength; 
byte[] tempImage = new byte[length]; 
myDBObject.ContentType = uploadFile.ContentType; 

uploadFile.InputStream.Read(tempImage, 0, length); 
myDBObject.ActualImage = tempImage ; 

HttpPostedFileBase의 InputStream 속성

희망이 도움이 있습니다.

+0

감사합니다 (그런데 IW_Attachment 내 데이터베이스 테이블 중 하나의 이름입니다) , 나는 그것에게 시도를주고, 당신에게 알릴 것이다. 감사! –

+0

글쎄, 실제로는 꽤 쉬웠다. –

2

감사합니다. kheit에게 감사드립니다. 마지막으로 작동 시켰습니다. 여기에 최종 해결책이 있습니다. 누군가를 도울 수 있습니다.

이 스크립트 방법은 디렉토리에서 모든 파일을 받아 데이터베이스에 업로드 :

 //upload all file from a directory to the database as blob 
     public void UploadFilesToDB(long UniqueId) 
     { 
      //directory path 
      string fileUnformatedPath = "../Uploads/" + UniqueId; //setting final path with unique id 

      //getting all files in directory (if any) 
      string[] FileList = System.IO.Directory.GetFiles(HttpContext.Server.MapPath(fileUnformatedPath)); 

      //for each file in direcotry 
      foreach (var file in FileList) 
      { 
       //extracting file from directory 
       System.IO.FileStream CurFile = System.IO.File.Open(file, System.IO.FileMode.Open); 
       long fileLenght = CurFile.Length; 

       //converting file to a byte array (byte[]) 
       byte[] tempFile = new byte[fileLenght]; 
       CurFile.Read(tempFile, 0, Convert.ToInt32(fileLenght)); 

       //creating new attachment 
       IW_Attachment CurAttachment = new IW_Attachment(); 
       CurAttachment.attachment_blob = tempFile; //setting actual file 

       string[] filedirlist = CurFile.Name.Split('\\');//setting file name 
       CurAttachment.attachment_name = filedirlist.ElementAt(filedirlist.Count() - 1);//setting file name 

       //uploadind attachment to database 
       SubmissionRepository.CreateAttachment(CurAttachment); 

       //deleting current file fromd directory 
       CurFile.Flush(); 
       System.IO.File.Delete(file); 
       CurFile.Close(); 
      } 

      //deleting directory , it should be empty by now 
      System.IO.Directory.Delete(HttpContext.Server.MapPath(fileUnformatedPath)); 
     } 

이 답변