2010-08-19 2 views
0

SqlConnection conn = 새 SqlConnection ("데이터 원본 = DDPRO8-WIN7X86 \ SQLEXPRESS; 초기 카탈로그 = mp3bytes; 보안 정보 유지 = True, 통합 보안 = true, 사용자 ID = ; "); SqlCommand cmd = null; SqlParameter param = null; cmd = 새 SqlCommand ("INSERT INTO mp3_bytes (노래)"+ "값 (@songs)", conn); FileStream fs = null;파일 업로드 컨트롤에서 파일 스트림으로 파일 이름 전달

string path = fileUpload.FileName; 
    fs = new FileStream(path, FileMode.Open, FileAccess.Read); 

    Byte[] song = new Byte[fs.Length]; 
    fs.Read(song, 0, song.Length); 
    fs.Close(); 
    param = new SqlParameter("@songs", SqlDbType.VarBinary, song.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, song); 
    cmd.Parameters.Add(param); 
    conn.Open(); 
    cmd.ExecuteNonQuery(); 
    conn.Close(); 
파일 업로드 파일 업로드 컨트롤입니다

.. 제가 mp3 파일을 업로드하고 .. 내가 어떻게 업로드에서 FILESTREAM하는 업로드 된 파일 이름을 전달할 수 있습니다 ''파일을 찾을 수 없습니다지고있어이를 실행할 때 fileUpload.HasFile 속성을 사용하여 업로드 된 모든 파일이 있으면 파일 제어 ..

당신을 감사합니다 ..

답변

2

사용 fileUpload.PostedFile.FileName 은 또한 더 나은 확인합니다. 또한 fileUpload.PostedFile.ContentLength> 0

편집에 대해 확인하여 제로 길이 파일을 방지 할 수 있습니다 - 다만 업로드 한 파일의 내용이 디스크에 당신을 구원 할 필요가 당신이하고있는 무슨 ... 실현 fileUpload.PostedFile.SaveAs 메서드를 사용합니다. 위의 파일 이름 속성은 클라이언트 컴퓨터에서 파일 이름을 제공하지만 파일은 서버에 존재하지 않습니다. 서버에 원하는 위치에 저장해야합니다. 예 :

이렇게하면 업로드 된 파일이 서버의 임시 디렉토리에 저장됩니다. 또한 파일 내용을 읽으려면 PostedFile.InputStream을 사용할 수 있습니다.

fs = new FileStream(path, FileMode.Open, FileAccess.Read); 웹 서버 컴퓨터에 파일이 없으므로 절대로 작동하지 않습니다.

편집 : 샘플 코드를 넣어 후FileStream fs = null; 및 이

var fs = uploadFile.PostedFile.InputStream; 

fs = new FileStream(path, FileMode.Open, FileAccess.Read); 

을 대체 제거하고 그 트릭을 할해야합니다.

+0

나는 이걸 시도 했지 .. – Leema

+0

하지만이 경우에는 데이터베이스에 바이트 배열로 mp3 파일을 저장해야 하나? – Leema

+0

안녕 thaaaaaanks 지금은 작동 ... – Leema

0

FileStream을 실제로 사용해야하는 경우 파일 열기가 아니라 파일 열기를 만들기보다는 파일 모드를 설정해야합니다. 파일을 만들면됩니다.

fs = new FileStream(path, FileMode.Create); 

편집 : 그러나, VinayC 말한대로, 다른 이름으로 저장()는 당신을위한 모든 노력을한다!

EDIT : 파일을 디스크에 저장 한 다음 파일에서 바이트를 읽어 SQL에 전달하는 것처럼 보입니다. FileUpload 컨트롤에서 FileBytes을 가져 와서 저장/읽기 부분을 건너 뛸 수 있습니다.

SqlConnection conn = new SqlConnection("Data Source=DDPRO8-WIN7X86\\SQLEXPRESS;Initial Catalog=mp3bytes;Persist Security Info=True;Integrated security=true; User ID=; Password=;"); 
SqlCommand cmd = null; 
SqlParameter param = null; 
cmd = new SqlCommand(" INSERT INTO mp3_bytes (songs) " + " Values (@songs) ", conn); 

param = new SqlParameter("@songs", SqlDbType.VarBinary, fileUpload.FileBytes.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, fileUpload.FileBytes); 
cmd.Parameters.Add(param); 
conn.Open(); 
cmd.ExecuteNonQuery(); 
conn.Close();