ASP MVC 2的文件上传到数据库中(BLOB) [英] ASP MVC 2 Uploading file to database (blob)
问题描述
我想通过表单上传文件,然后在SQL保存为一个blob。
I am trying to upload a file via a form and then save in in SQL as a blob.
我已经有我的形式工作的罚款,我的数据库是完全可以采取的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);
}
现在所有我缺少的是把文件在数据库中。我不能对这个问题找到任何东西...我发现一些方法来做到这一点在一个普通的网站,但没有在MVC2。
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!
感谢您。
推荐答案
这可以帮助:<一href=\"http://byatool.com/mvc/asp-net-mvc-upload-image-to-database-and-show-image-dynamically-using-a-view/\">http://byatool.com/mvc/asp-net-mvc-upload-image-to-database-and-show-image-dynamically-using-a-view/
既然你在你的控制器方法有HttpPostedFileBase,所有你需要做的是:
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拥有的InputStream属性
HttpPostedFileBase has a InputStream property
希望这有助于。
这篇关于ASP MVC 2的文件上传到数据库中(BLOB)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!