2015-01-15 10 views
0

사용자가 파일을 프로젝트에 첨부 할 수있게하고 싶습니다. 파일은 이미지, 문서, 텍스트, zip 파일 등이 될 수 있습니다.SQL Server 데이터베이스와의 파일 저장/검색

파일 이름, 확장명, 크기, 파일에 대한 설명 및 파일 데이터를 저장할 테이블을 데이터베이스에 만들었습니다. 파일 데이터의 열 유형은 VarBinary (blob)입니다.

이제 사용자 입력을 가져 와서 로컬 목록 뷰 (db에 바인딩되지 않음)에 저장했습니다. 목록보기 행을 반복하여 데이터베이스에 저장하려고합니다. BLOB 열에 파일 데이터를 어떻게 저장해야합니까?

+1

사용 VARBINARY 데이터 유형에 추가하십시오. 이 링크를 확인하십시오 : http://www.codeproject.com/Articles/468198/Store-Images-in-SQL-Server –

답변

1

// **** Read File/Image into Byte Array from Filesystem 
     public static byte[] GetPhoto(string filePath) 
     { 
      FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); 
      BinaryReader br = new BinaryReader(fs); 

      byte[] photo = br.ReadBytes((int)fs.Length); 

      br.Close(); 
      fs.Close(); 

      return photo; 
     } 

이 그런 기능 위의 호출이 데이터베이스

// **** Read Image from Filesystem and add it to the Database. 
     public void AddFileDataIntoDatabase(
      string a,string b,string c, string photoFilePath) 
     { 

      // Read Image into Byte Array from Filesystem 
      byte[] photo = GetPhoto(photoFilePath); 

      // Construct INSERT Command 
      SqlCommand addEmp = new SqlCommand(
       "INSERT INTO tablename ("+ 
       "col1,col2,Col3,Photo) "+ 
       "VALUES(@col1,@col2,@col3,@Photo)",_conn); 

      addEmp.Parameters.Add("@col1", SqlDbType.NVarChar, 20).Value = plastName; 
      addEmp.Parameters.Add("@col2", SqlDbType.NVarChar, 10).Value = pfirstName; 
      addEmp.Parameters.Add("@col3",  SqlDbType.NVarChar, 30).Value = ptitle;     
      addEmp.Parameters.Add("@Photo",  SqlDbType.Image, photo.Length).Value = photo; 

      // Open the Connection and INSERT the BLOB into the Database 
      _conn.Open(); 
      addEmp.ExecuteNonQuery(); 
      _conn.Close(); 
     } 

Refer here

+0

전체 BLOB를'byte []'에 읽거나 쓰는 것을 권장하지 않습니다; 기가 바이트 수 있습니다. 나는'SequentialAccess'를 사용할 것을 제안한다. –

0
SELECT * FROM OPENROWSET(BULK N'<FILEPATH>', SINGLE_BLOB) AS Contents 
It'll pull in the contents of the file as varbinary.