Search code examples
c#uploadmp3

Pass file name from file upload control to filestream


    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);
    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();

where fileUpload is the file upload control. I am uploading an mp3 file. When I execute this I'm getting could not find file '', how can I pass the uploaded filename to filestream from upload file control?


Solution

  • Use fileUpload.PostedFile.FileName

    Also its better to check if there is any file that has been uploaded using fileUpload.HasFile property. You can also guard against zero length files by checking against fileUpload.PostedFile.ContentLength > 0.

    Edit: just realized your mistake

    The uploaded file content needs to saved by you on the disk using fileUpload.PostedFile.SaveAs method. The above file name property will give you file name on the client machine, but the file will not exist on the server. You need to save it wherever you want on server. For example,

    var path = Path.Combine(tempDirectory, fileUpload.PostedFile.FileNam);
    fileUpload.PostedFile.SaveAs(path);
    

    This would put the uploaded file in the temp directory on the server. You can also use PostedFile.InputStream to read file contents.

    fs = new FileStream(path, FileMode.Open, FileAccess.Read); will never work as file does not exist on web server machine.

    Edit: based on your sample code

    Remove FileStream fs = null; and replace

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

    with

    var fs = uploadFile.PostedFile.InputStream;
    

    and that should do the trick.