ASP. 4-Upload image to database

Source: Internet
Author: User
Tags connectionstrings

Here's how to upload a picture to a database in an MVC Web application and how to display a picture on a Web page. The database table corresponds to the entire model class, not only the picture data a field, we start with the definition of the data table:

CREATE TABLE [dbo]. [Products] (    [ProductID]     INT             IDENTITY (1, 1) not NULL,    [Name]          NVARCHAR (MAX)  is not null,    [Description ]   NVARCHAR (max) not  null,    [price]         DECIMAL (2) is not NULL,    [Category]      NVARCHAR (max) Not  NULL,    [ImageData]     VARBINARY (max) null,    [Imagemimetype] NVARCHAR (max)  null,    CONSTRAINT [pk_dbo. Products] PRIMARY KEY CLUSTERED ([ProductID] ASC));

The fields that save the picture are ImageData, type varbinary, field Imagemimetype Save the type of picture. We use the Entity Framework to handle C # objects to the database, and we do not need to write code to manipulate the database through SQL code, the Entity Framework is responsible for the operation of the database. The Entity framework supports model first and Code-first two ways, Code-first write the C # model class, and then bind to the database, the related content can be see http://msdn.microsoft.com/ en-us/data/jj200620.

Start with the Model class:

public class Product {        [Hiddeninput (Displayvalue = false)] public        int ProductID {get; set;}        [Required (errormessage = "Please enter a product name")]        public string Name {get; set;}        [DataType (Datatype.multilinetext)]        [Required (errormessage = "Please enter a description")]        public string Description {get; set;}        [Required]        [Range (0.01, double. MaxValue, errormessage = "Please enter a positive price")] public         decimal price {get; set;}        [Required (errormessage = "Please specify a category")]        public string Category {get; set;}        Public byte[] ImageData {get; set;}        [Hiddeninput (Displayvalue = false)]        public string Imagemimetype {get; set;}    }

The Entity Framework can be installed with the NuGet Package Manager in VS, and the Entity Framework is installed and we create the session class for the Entity Framework to associate the model with the database:

Using System.data.entity;namespace SportsStore.Domain.Concrete {public    class Efdbcontext:dbcontext {        public Dbset<product> products {get; set;}}    }

We also need to tell the Entity Framework which database to use, and add the appropriate connection string to the Web. config:

...<connectionstrings>    <add name= "Efdbcontext" connectionstring= "Data source= (localdb) \v11.0;Initial catalog=sportsstore;integrated security=true "providername=" System.Data.SqlClient "/>  </ Connectionstrings>, .....

Next, create an auxiliary class that uses Efdbcontext to manipulate the model:

Public interface Iproductrepository {iqueryable<product> products {get;}        void Saveproduct (product product);    Product deleteproduct (int productID);        }public class Efproductrepository:iproductrepository {private Efdbcontext context = new Efdbcontext (); Public iqueryable<product> Products {get {return context. Products; }} public void Saveproduct (product product) {if (product. ProductID = = 0) {context.            Products.add (product); } else {Product Dbentry = context. Products.find (product.                ProductID); if (dbentry! = null) {Dbentry.name = product.                    Name; Dbentry.description = product.                    Description; Dbentry.price = product.                    Price; Dbentry.category = product.                    Category; Dbentry.imagedata = product. ImagedAta Dbentry.imagemimetype = product.                Imagemimetype; }} context.        SaveChanges (); Public Product deleteproduct (int productID) {Product Dbentry = context.            Products.find (ProductID); if (dbentry! = null) {context.                Products.remove (Dbentry); Context.            SaveChanges ();        } return dbentry; }    }

The

Definition Iproductrepository interface is convenient for subsequent use of dependency injection to obtain an instance of the implementation class efproductrepository from the interface, and this does not list how specifically to implement it. Efproductrepository uses Efdbcontext to finish adding, saving objects to the database, and deleting objects from the database. To complete the operation of the data model, the following method defines the controller:

    public class Admincontroller:controller {private Iproductrepository repository;        Public Admincontroller (Iproductrepository repo) {repository = repo; Public ViewResult Index () {return View (repository.        Products); Public ViewResult Edit (int productId) {Product Product = Repository. Products.            FirstOrDefault (p = P.productid = = ProductID);        return View (product); } [HttpPost] public actionresult Edit (product product, HttpPostedFileBase image) {if (modelstate . IsValid) {if (image! = null) {product. Imagemimetype = image.                    ContentType; Product. ImageData = new Byte[image.                    ContentLength]; Image. Inputstream.read (product. ImageData, 0, image.                ContentLength); } repository.                Saveproduct (product); tempdata["message"] = string. Format ("{0} has been sAved ", product.                Name);            Return redirecttoaction ("Index");            } else {//There is something wrong with the data values return View (product);        }} public ViewResult Create () {return View ("Edit", New Product ()); } [HttpPost] public actionresult Delete (int productId) {Product deletedproduct = repository.            Deleteproduct (PRODUCTID); if (deletedproduct! = null) {tempdata["message"] = string.            Format ("{0} was deleted", deletedproduct.name);        } return Redirecttoaction ("Index"); }    }

Here two edit ation, the first to display the Edit upload page, with the HttpPost feature for processing the editing page submission callback, the submitted image data is the HttpPostedFileBase type, The data from which we extracted the image file is saved to the ImageData property of the model class, and ContentType is logged to the Imagemimetype property. Corresponding Edit view:

@model sportsstore.domain.entities.product@{    viewbag.title = "Admin:edit" + @Model. Name;    new {enctype = "multipart/form-data"})) {        @Html. Editorformodel ()    <div class= "Editor-label" >Image</div>    <div class= " Editor-field ">        @if (model.imagedata = = null) {            @:none        } else {                    }        <div>upload new Image: <input Type= "File" Name= "Image"/></div>    </div>            <input type= "Submit" value= "Save"/>    @ Html.ActionLink ("Cancel and Return to List", "Index")}

The enctype=multipart/form-data of the form is specified here, and the data submitted by this attribute form is missing only the name of the picture file and not the picture file. The image shows that the IMG element src points to a URL generated from the action of product, and we also need to implement this method:

This returns a filecontentresult from the picture file data and MIME type.

This is the implementation of the upload image to the database complete process, the actual application we also need to limit the file size, through the file suffix name or contenttype check whether it is a valid picture file.

The above is part of the fourth edition of Apress Pro ASP 4, as described in the original http://www.apress.com/9781430242369.

ASP. 4-Upload image to database

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.