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

发布于 2024-09-14 02:55:16 字数 1794 浏览 4 评论 0原文

我正在尝试通过表单上传文件,然后将其作为 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 中没有找到任何方法。

欢迎任何形式的帮助!

谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

诗酒趁年少 2024-09-21 02:55:16

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

希望这会有所帮助。

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.

无声静候 2024-09-21 02:55:16

好吧,多亏了 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 是我的一个数据库表的名称)

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文