上传asp.net MVC 2中的图像/文件

时间:2010-09-07 09:51:43

标签: asp.net-mvc-2

如何创建环境来选择图像文件并将其上传到asp.net MVC 2中?我必须为此写出什么代码?

哪种情况更好:

将图像存储在数据库中还是在应用程序域的文件系统中保留图像副本并在DB中保留其路径?什么代码必须在asp.net MVC 2中编写首选方案?

3 个答案:

答案 0 :(得分:2)

您可以尝试此链接
http://weblogs.asp.net/imranbaloch/archive/2010/04/03/image-preview-in-asp-net-mvc.aspx
它附有样品项目。如果你有大量的图片,你可以存储在文件系统中。我认为这取决于您的情况

答案 1 :(得分:1)

Html代码

file to upload: <input type="file" name="Photo" id="Photo" />

C#

  public ActionResult Imageupload(MyObject myObject )
        {
            //PhotoForSingleItem is just a class that has properties
            // Name and Alternate text.  I use strongly typed Views and Actions
            //  because I'm not a fan of using string to get the posted data from the
            //  FormCollection.  That just seems ugly and unreliable to me.

            //PhotoViewImage is just a Entity framework class that has
            // String Name, String AlternateText, Byte[] ActualImage,
            //  and String ContentType

            HttpPostedFileBase file = Request.Files["Photo"];
            //newImage.Name = photo.Name;
            //  newImage.Alt = photo.AlternateText;

            //Here's where the ContentType column comes in handy.  By saving
            //  this to the database, it makes it infinitely easier to get it back
            //  later when trying to show the image.
            //patient.photo = file.ContentType;

            Int32 length = file.ContentLength;
            //This may seem odd, but the fun part is that if
            //  I didn't have a temp image to read into, I would
            //  get memory issues for some reason.  Something to do
            //  with reading straight into the object's ActualImage property.

            try
            {
                if (length != 0)
                {
                    if ((file.ContentType == "image/pjpeg") || (file.ContentType == "image/gif") || (file.ContentType == "image/x-png"))
                    {
                        byte[] tempImage = new byte[length];


                        file.InputStream.Read(tempImage, 0, length);




                        localRepository.SaveOrUpdate(myObject);// you can insert through sql commands. 
}
catch(Exception ex){

}
      return View()
}

答案 2 :(得分:1)

这是一个非常零的代码解决方案,用于在数据库中存储文件

http://sfvt.wordpress.com/2010/09/07/asp-net-tutorial-detailsview-insert-imag-binary-database/

享受