Springmvc+mybatis processing Picture (a): Upload image

Source: Internet
Author: User

Always feel that uploading image files and so on is very difficult, so the final processing of pictures, found that it is not so difficult to start the text.

Idea: Save the file of the foreground upload to the Mutipartfile type field, then convert the Mulipartfile to the byte[] array in the Pojo class, and finally into the database Longblob type field
1. Database design, set the picture newspic field type to Longblob or blob

2. Prepare the jar package: Commons-fileupload and Commons-io, I use Commons-fileupload-1.3.1.jar and Commons-io-2.4.jar, can also be downloaded here.
3. Configuring the Upload file in Springmvc-config.xml

class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" >    <property name= " Defaultencoding ">        <value>UTF-8</value>    </property>    <property name=" Maxuploadsize ">        <value>32505856</value><!--upload file size limit 31m,31*1024*1024---    </ property>    <property name= "maxinmemorysize" >        <value>4096</value>    </property ></bean>

When you upload a file in a form form, you must specify the Enctype property value as Multipart/form-data, which means that the file is transferred as a binary stream. Otherwise the error will not be uploaded.
Because the enctype= "Multipart/form-data" attribute is added to the form form, the data is converted to binary, resulting in a null value for the received value, so configure the Multipartresolver in the spring configuration file
4. addnews.jsp

enctype= "Multipart/form-data">    <table>        <tr>            <td>                name= " Newspicture "/>            </td>        </tr>        <!--omitting the code for other fields--    </table></form >

5. Newsmapper.java and Newsdynasqlprovider.java
(1) Newsmapper.java

// Insert News @SelectProvider dynamically (Type=newsdynasqlprovider.  Class, method= "Insertnews")void Save (news News);

(2) Newsdynasqlprovider.java

//Dynamic Insertion PublicString Insertnews (FinalNews News) {    return NewSQL () {{Insert_into ("News"); if(News.getnewstitle ()! =NULL&&!news.getnewstitle (). Equals ("") {VALUES ("Newstitle", "#{newstitle}"); }            if(News.getnewsabstract ()! =NULL&&!news.getnewsabstract (). Equals ("") {VALUES ("Newsabstract", "#{newsabstract}"); }            if(News.getnewsauthor ()! =NULL&&!news.getnewsauthor (). Equals ("") {VALUES ("Newsauthor", "#{newsauthor}"); }            if(News.getnewstime ()! =NULL&&!news.getnewstime (). Equals ("") {VALUES ("Newstime", "#{newstime}"); }            if(News.getnewscontent ()! =NULL&&!news.getnewscontent (). Equals ("") {VALUES ("Newscontent", "#{newscontent}"); }            if(News.getnewspic ()! =NULL&&!news.getnewspic (). Equals ("") {VALUES ("Newspic", "#{newspic,jdbctype=blob}"); }}}.tostring ();}

6. Testservice.java and Testserviceimpl.java
(1) Testservice.java

/**@param @throws */void throws Exception;

(2) Testserviceimpl.java

@Override  Public void multipartfile newspic throws Exception {    byte[] B1 =   newspic.getbytes ();    News.setnewspic (B1);    Newsmapper.save (news);}

7. Newscontroller.java

/*** Process Add request *@paramString flag Flag, 1 for Jump to add page, 2 for add action *@paramNews Headlines to add *@paramModelandview MV *@throwsException **/@RequestMapping (Value= "/addnewst")  PublicModelandview Addnewst (String flag, @ModelAttribute News news,multipartfile newspicture, Modelandview MV, HttpSession session)throwsexception{if(Flag.equals ("1") {mv.setviewname ("Addnews"); }Else{testservice.addnewsandpic (news, newspicture); Mv.setviewname ("Redirect:/htnews"); }     returnMV;}

8. News.java

 Public classNewsImplementsserializable{PrivateInteger NewsID; PrivateString Newstitle; PrivateString newsabstract; PrivateString Newsauthor; @DateTimeFormat (Pattern= "Yyyy-mm-dd HH:mm:ss")    PrivateDate Newstime; PrivateString newscontent; Private byte[]Newspic;//News Photos         PublicNews () {Super(); }    //Setter and Getter}

Ref: 50413864
Second,. JSP improved, after reading the path of the Input:file, display the local picture

#imagePreview {width:160px;   height:120px; Filter:progid:DXImageTransform.Microsoft.AlphaImageLoader (Sizingmethod=Scale ); }   </style>var loadimagefile=(function () {if(window. FileReader) {var opreviewimg=NULL, Ofreader =Newwindow. FileReader (), Rfilter=/^ (?: image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\ /png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap |image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\- Xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump) $/i; Ofreader.onload=function (ofrevent) {if(!opreviewimg) {var Newpreview= document.getElementById ("Imagepreview"); Opreviewimg=NewImage (); OPreviewImg.style.width= (newpreview.offsetwidth). toString () + "px"; OPreviewImg.style.height= (newpreview.offsetheight). toString () + "px";       Newpreview.appendchild (OPREVIEWIMG); } opreviewimg.src=OFREvent.target.result;                   }; returnfunction () {var afiles= document.getElementById ("Imageinput"). files; if(Afiles.length = = 0) {return; } if(!rfilter.test (Afiles[0].type)) {Alert ("You must select a valid Image file!");return; } Ofreader.readasdataurl (afiles[0]); }                   }       if(Navigator.appname = = = "Microsoft Internet Explorer") {       returnfunction () {alert (document.getElementById ("Imageinput"). Value); document.getElementById ("Imagepreview"). Filters.item ("DXImageTransform.Microsoft.AlphaImageLoader"). src = document.getElementById (" Imageinput "). Value;   }       }       })(); </script></body>

Effect

Ref: 38046939

------------------------------------------------------Dividing line------------------------------------------------------------
Error encountered:
1. After the Springmvc form is submitted, the controller receives a value of NULL,


The error is as follows:

April, 2018 10:43:33 for Servlets [SPRINGMVC] in the context with path [/   Java.lang.NullPointerException] with root Causejava.lang.NullPointerExceptionat Com.game.controller.NewsController.addNewst (Newscontroller.java:58)

Cause: No configuration multipartresolver, ref: 79076455

------------------------------------------------------Dividing line------------------------------------------------------------

BLOB data types in MySQL
In a computer, a blob is a field type that is often used to store binary files in a database, a typical blob is a picture or a sound file.
In MySQL, BLOBs are a series of types, including: Tinyblob, BLOBs, Mediumblob, Longblob, the only difference between these types is the maximum size of the storage file.

Type Size (units: bytes)
Tinyblob Maximum 255
Blob 65K Max
Mediumblob 16M Max
Longblob 4G Max

Springmvc+mybatis processing Picture (a): Upload image

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.