gavriel ankri

gavriel ankri

  • NA
  • 39
  • 48.5k

How to store image/any files into a SQL database

Dec 24 2011 2:52 AM
Hello
I am trying to upload files into a SQL database.  the transfer is moving to the selected folder, but it doesnt appear in my Sql table.   I am using  VARBINARY(MAX).
this is my code:


   public void Uploadfile(RemoteFileInfo response)
        {
            FileStream targetStream = null; //write -> to server
            Stream sourceStream = response.FileByteStream; // from the client

            string filePath = Path.Combine(serverFilesFolder, response.FileName);

            byte[] buffer;

            using (targetStream = new FileStream(
                                    filePath, FileMode.Create, FileAccess.Write))
            {

                //Creating the uploaded file:

                const int bufferLength = 65000;
                buffer = new byte[bufferLength];
                int count;

                //Loop: Reading --> Writing
                while ((count = sourceStream.Read(buffer, 0, bufferLength)) > 0)
                {
                    targetStream.Write(buffer, 0, count);
                    Console.WriteLine("Writing {0:n0} Bytes", count); //for my tracing...

                   
                }
                      // Store in Database

                    context.AddToFileTableNew(new FileTableNew             
                    {
                        FileName = response.FileName,
                        Size = response.Length,
                        UserName = response.UserName,
                        FileData = buffer
                    });
                    context.SaveChanges();

                    targetStream.Close();
                    sourceStream.Close();



Answers (2)