views:

103

answers:

2

Hi, I am trying to upload a file via a form and then save in in SQL as a blob.

I already have my form working fine, my database is fully able to take the blob and I have a controller that take the file, saves it in a local directory:

[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);
        }

Now all I am missing is putting the file in the database. I could not find anything on the subject... I found some way to do it in a regular website but nothing in MVC2.

Any kind of help would be welcome!

Thank you.

+2  A: 

This could help: http://byatool.com/mvc/asp-net-mvc-upload-image-to-database-and-show-image-dynamically-using-a-view/

Since you have HttpPostedFileBase in your controllers method, all you need to do is:

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

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

HttpPostedFileBase has a InputStream property

Hope this helps.

kheit
Thanks for this answer, I'll give it a try and let you know. Thanks!
Lobsterm
Well It worked, it was actually pretty easy thank you very much.
Lobsterm
A: 

Alright thanks to kheit, I finaly got it working. Here's the final solution, it might help someone out there.

This script method takes all the file from a directory and upload them to the database:

        //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));
        }

(By the way IW_Attachment is the name of one of my database table)

Lobsterm