Upload images to SQL Server 2005 using ASP.Net MVC?

前端 未结 4 1038
闹比i
闹比i 2021-01-14 06:53

I know there is a way to upload images to the database as image type or varbinary type, however, I searched around the entire week, I am unable to find anything that can hel

4条回答
  •  Happy的楠姐
    2021-01-14 07:41

    You should be able to access the Request's File collection and obtain an HttpPostedFile instance for each uploaded file. Grab the InputStream from the file and read it into the byte array for the column property. I'm assuming this is how your DAL maps the varbinary to your business class -- if not, say it's a native Image, then you'll need to do the conversion before saving. The example below uses LINQ2SQL.

    MyClass obj = new MyClass();
    obj.Name = Request["name"];   // other properties
    obj.Alt = Request["altText"];
    
    HttpPostedFile file = Request.Files[0];
    if (file != null)
    {
         obj.Image image = new byte[file.ContentLength];
         file.Read(obj.Image,0,file.ContentLength];
    }
    
    using (DataContext context = new DataContext())
    {
        context.InsertOnSubmit( obj );
        context.SubmitChanges();
    }
    

提交回复
热议问题