MyBatis and SPRINGMVC to achieve file upload, download function _java

Source: Internet
Author: User
Tags save file

Environment: MAVEN+SPRINGMVC + Spring + mybatis + MySql

This article mainly explains how to use input to upload files to the server specified directory, or save to the database, how to download files from the database, and display image files and zoom.

Stores a file in a database, typically a byte array of stored files, and a blob for the corresponding database data type.

First you create the database, where you use the MySQL database.

Note: The code given in this paper is an excerpt of important fragments, not complete.

1. Preliminary preparation

Use Maven to create a Springmvc+spring+mybatis+mysql project.

For information on how to integrate Spring+mybatis+mysql, see MyBatis Profile and Configuration mybatis+spring+mysql:

A brief introduction and configuration of MyBatis learning, MyBatis mybaits+spring+mysql

For the construction of the SPRINGMVC environment, see: The SPRINGMVC project to build maven using eclipse:

Building MAVEN's SPRINGMVC project with Eclipse

In the foreground HTML, the enctype of the form is multipart/form-data. Note that the name of input, select, and the members of the studentform correspond to each.

The uploaded URL is addaction.do, and studentform is used to map the submitted data in the parameters of this action method. The data for the submitted file can be obtained at this time. Then we operate on the file.

Create PHOTO_TBL Table: Photo_data fields are used to hold files, type MyBatis Longblob, and then write mapper Java interface photomapper: including additions and deletions Mapper XML file: An SQL statement that corresponds to a Java interface.

and requires the spring configuration file to add a bean declaration.

The following is an HTML, action, Studentform snippet, and the SQL, Photomapper.java interface code, photomapper.xml file code to create the PHOTO_TBL table.

Form form forms for 1.1 html

1.<form action= "<c:url value= ' addaction.do '/>" method= "post" enctype= "Multipart/form-data" > 
2. < Table> 
3 <tr> 
4 width= "<TD" align= "right" > Photo:</td> 
5. <td><input Type= "File" Name= "Studentphoto"/></td> 
6 </tr> 
7 </table> 8 <input type= 
" Submit "> 

1.2 Action method

1./** 
2. * Add-Submit 
3. * 
4 @RequestMapping (value = "addaction.do") 
5.public String add_action (modelmap Model, Studentform form) { 
6. 

1.3 Studentform Class

1.package Liming.student.manager.web.model; 
2. 
3.import org.springframework.web.multipart.MultipartFile; 
4. 
5.public class Studentform extends Generalform { 
6. 
7. Private String Studentname; 
8. private int studentsex; 
9. Private String Studentbirthday; 
Private Multipartfile Studentphoto; 
11. 

1.4 Creating PHOTO_TBL

1.CREATE TABLE photo_tbl 
2. ( 
3. photo_id VARCHAR (MB) PRIMARY KEY, 
4. Photo_data Longblob, 
5. file_name VARCHAR (10) 

1.5 Photomapper interface

1. @Repository 
2 @Transactional 
3.public interface Photomapper { 
4. 
5. public void Createphoto (photoentity entity); 
6. 
7. public int deletephotobyphotoid (String photoid); 
8. 
9. public int updatephotodate (@Param ("PhotoID") String photoid, @Param ("Photodate") byte[] photodate); 
A 
. Public photoentity getphotoentitybyphotoid (String photoid); 
12. 

1.6 Photomapper.xml File

Including the increase, delete, change, check. The new photoid uses the MySQL custom function to automatically generate the primary key. You need to develop Typehandler as "Org.apache.ibatis.type.BlobTypeHandler" when manipulating blobs. The INSERT, update time parameter needs to be specified after the Resultmap.

1.<?xml version= "1.0" encoding= "UTF-8"?> 2.<! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 3.< Mapper namespace= "Liming.student.manager.data.PhotoMapper" > 4. <resultmap type= "liming.student.manager.data.model.PhotoEntity" id= "Photomapper_resultmap_photoentity" > 5. <id property= "PhotoID" column= "photo_id" javatype= "String" jdbctype= "VARCHAR"/> 6. <result property= "Photodata" column= "Photo_data" javatype= "byte[" "jdbctype=" BLOB "typehandler=" Org.apache.ibatis.type.BlobTypeHandler "/> 7. <result property= "FileName" column= "file_name" javatype= "String" jdbctype= "VARCHAR"/> 8. 
</resultMap> 9. <insert id= "Createphoto" parametertype= "liming.student.manager.data.model.PhotoEntity" > 11. <selectkey keyproperty= "PhotoID" resulttype= "String" order= "before" > 12. Select Nextval (' photo ') 13. </selectKey> 14. INSERT into Photo_tbl (photo_id, 15. Photo_data,
file_name) 17. VALUES (#{photoid, Jdbctype=varchar}, #{photodata, javatype=byte[], Jdbctype=blob, typehandler= Org.apache.ibatis.type.BlobTypeHandler}, 19. #{filename, Jdbctype=varchar}) 20. 
</insert> 21. <delete id= "Deletephotobyphotoid" > 23. DELETE from Photo_tbl 24. WHERE photo_id = #{photoid, Jdbctype=varchar} 25. 
</delete> 26. <update id= "Updatephotodata" > 28. UPDATE Photo_tbl 29. 
SET photo_data = #{photodata, javatype=byte[], Jdbctype=blob, Typehandler=org.apache.ibatis.type.blobtypehandler}, file_name = #{filename, Jdbctype=varchar} 31. WHERE photo_id = #{photoid, Jdbctype=varchar} 32. 
</update> 33. <select id= "getphotoentitybyphotoid" resultmap= "photomapper_resultmap_photoentity" > 35. SELECT photo_id, 36. Photo_data, 37. File_name 38. From PHOTO_TBL 39. WHERE photo_id = #{photoid, Jdbctype=varchar} 40.  </select> 41.</mapper>

1.7 Spring configuration file

A declaration that requires the spring configuration file to add a org.springframework.web.multipart.commons.CommonsMultipartResolver bean.

1.<bean id= "Multipartresolver" class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" > 
2. <property name= "maxuploadsize" value= "1073741824"/> 

2. Put the file on the server

1.private static final String Uploadfilepath = "d:\\temp_upload_file\\"; 2.3./** 4. * Add-Submit – Save only files to server 5.  * * 6 @RequestMapping (value = "addaction.do") 7.public String add_action (modelmap model, studentform form) {8.try {9. 
Multipartfile UploadFile = Form.getstudentphoto (); 
String filename = Uploadfile.getoriginalfilename (); 
InputStream is = Uploadfile.getinputstream (); 12.//If the server already exists and uploads files with the same name, the output message 13. 
File Tempfile = new file (uploadfilepath + filename); 
if (tempfile.exists ()) {A Boolean delresult = Tempfile.delete (); 
System.out.println ("Delete existing files:" + Delresult); 17.} 18. Start saving files to server 19. if (!filename.equals ("")) {20. 
FileOutputStream fos = new FileOutputStream (uploadfilepath + filename); byte[] buffer = new byte[8192]; Read 8K byte 22 at a time. 
int count = 0; 23.//Start reading the bytes of the uploaded file and outputting it to the server's upload file output stream 24. 
while (count = is.read (buffer)) > 0) {fos.write (buffer, 0, count);//write Byte stream to server-side file 26.} Fos.close (); Close FileoutputstreAm Object 28. Is.close (); InputStream Object 29. } 30. 
catch (FileNotFoundException e) {e.printstacktrace (); 
The catch (IOException e) {e.printstacktrace ();  34.} 35.}

3. Upload the file to the database

1./** 
2. * Add-Submit – Save file to Database 
3. 
/4 @RequestMapping (value = "addaction.do") 
5.public String add_action ( Modelmap model, Studentform form) { 
6. InputStream is = Form.getstudentphoto (). getInputStream (); 
7. byte[] Studentphotodata = new byte[(int) Form.getstudentphoto (). GetSize ()]; 
8. Is.read (studentphotodata); 
9. String fileName = Form.getstudentphoto (). Getoriginalfilename (); 
Photoentity photoentity = new photoentity (); 
Photoentity.setphotodata (studentphotodata); 
Photoentity.setfilename (fileName); 
This.photoMapper.createPhoto (photoentity); 

4. Download the file

The download file requires that the byte array be restored to a file.

First use MyBatis to isolate the byte array in the database, specifying the filename (including the format). Then use OutputStream to enter the file

 
 
 

5. Display byte picture file

1. @RequestMapping (value = "Getphotobyid") 
2.public void Getphotobyid (String ID, final httpservletresponse response ) { 
3. photoentity entity = this.photoMapper.getPhotoEntityByPhotoId (ID); 
4. byte[] data = Entity.getphotodata (); 
5. Response.setcontenttype ("Image/jpeg"); 
6. Response.setcharacterencoding ("UTF-8"); 
7. OutputStream Outputsream = Response.getoutputstream (); 
8. InputStream in = new Bytearrayinputstream (data); 
9. int len = 0; 
byte[] buf = new byte[1024]; 
One. while (len = In.read (buf, 0, 1024))!=-1) { 
outputsream.write (buf, 0, Len); 
Outputsream.close (); 
 
 

6. Scale picture by aspect scale

1. @RequestMapping (value = "getphotoid") 2.public void Getphotobyid (String id, int width, int height, final httpservletr Esponse response) {3. 
photoentity entity = this.photoMapper.getPhotoEntityByPhotoId (ID); 
4. byte[] data = Entity.getphotodata (); 
5. If (width!= 0 && height!= 0) {6 data = scaleimage (data, width, height); 7.} 8. 
Response.setcontenttype ("Image/jpeg"); 
9. Response.setcharacterencoding ("UTF-8"); 
OutputStream Outputsream = Response.getoutputstream (); 
InputStream in = new Bytearrayinputstream (data); 
int len = 0; 
byte[] buf = new byte[1024]; 
while (len = In.read (buf, 0, 1024))!=-1) {outputsream.write (buf, 0, Len); 16.} 17. 
Outputsream.close (); 
18.} 19. 20.public Static byte[] Scaleimage (byte[] data, int width, int height) throws IOException {21. 
BufferedImage buffered_oldimage = Imageio.read (new Bytearrayinputstream (data)); 
int imageoldwidth = Buffered_oldimage.getwidth (); imageoldheight int = Buffered_oldimage.getheight (); 
Double scale_x = (double) width/imageoldwidth; 
Double scale_y = (double) height/imageoldheight; 
Double scale_xy = Math.min (scale_x, scale_y); 
An. int imagenewwidth = (int) (imageoldwidth * scale_xy); 
int imagenewheight = (int) (imageoldheight * scale_xy); 
BufferedImage buffered_newimage = new BufferedImage (Imagenewwidth, Imagenewheight, Bufferedimage.type_int_rgb); Buffered_newimage.getgraphics (). DrawImage (Buffered_oldimage.getscaledinstance (Imagenewwidth, ImageNewHeight, 
Bufferedimage.scale_smooth), 0, 0, NULL); 
Buffered_newimage.getgraphics (). Dispose (); 
Bytearrayoutputstream outputstream = new Bytearrayoutputstream (); 
Imageio.write (buffered_newimage, "JPEG", outputstream); 
return Outputstream.tobytearray ();  35.}
 
 

The above is a small set to introduce MyBatis and SPRINGMVC together to achieve file upload, download function, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.