ASP MVC 2将文件上传到数据库(blob)

时间:2010-08-11 18:32:15

标签: sql asp.net-mvc-2 file-upload blob

我正在尝试通过表单上传文件,然后将其作为blob保存在SQL中。

我的表单工作正常,我的数据库完全能够获取blob,我有一个控制器来获取文件,将其保存在本地目录中:

[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 个答案:

答案 0 :(得分:5)

这可能会有所帮助: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属性

希望这有帮助。

答案 1 :(得分:2)

好的,谢谢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是我的数据库表之一)