ASP MVC 2 Загрузка файла в базу данных (блоб) - PullRequest
1 голос
/ 11 августа 2010

Я пытаюсь загрузить файл через форму, а затем сохранить его в SQL в виде большого двоичного объекта.

Моя форма уже работает нормально, моя база данных полностью в состоянии принять большой двоичный объект, и у меня естьКонтроллер, который принимает файл, сохраняет его в локальном каталоге:

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

Теперь все, что мне не хватает - это поместить файл в базу данных.Я не мог найти что-либо по этому вопросу ... Я нашел какой-то способ сделать это на обычном веб-сайте, но ничего в MVC2.

Любая помощь будет приветствоваться!

Спасибо.

Ответы [ 2 ]

5 голосов
/ 11 августа 2010

Это может помочь: http://byatool.com/mvc/asp-net-mvc-upload-image-to-database-and-show-image-dynamically-using-a-view/

Так как в вашем методе контроллеров есть HttpPostedFileBase, все, что вам нужно сделать, это:

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

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

HttpPostedFileBase имеет свойство InputStream

Надеюсь, это поможет.

2 голосов
/ 13 августа 2010

Хорошо, благодаря kheit, я наконец-то получил его на работу.Вот окончательное решение, оно может кому-то помочь.

Этот метод сценария берет все файлы из каталога и загружает их в базу данных:

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

(Кстати, IW_Attachmentимя одной из моих таблиц базы данных)

...