Environment: maven+SpringMVC + Spring + MyBatis + MySql
This article mainly explains how to use input to upload files to the specified directory of the server, or save them to the database; how to download files from the database, display image files and achieve scaling.
Store files in a database, generally a byte array that stores files, and the corresponding database data type is blob.
First, you need to create a database, here you use the MySql database.
Note: The code given in the article is mostly excerpted and not complete.
1. Preparation
Use maven to create a springMVC+spring+mybatis+mysql project.
For how to integrate Spring+mybatis+mysql, see the introduction of MyBatis and configure MyBatis+Spring+MySql:
MyBatis Learning One, Introduction and Configuration of MyBatis MyBatis + Spring + MySql
For the construction of SpringMVC environment, please see: Use Eclipse to build Maven's SpringMVC project:
Build Maven's SpringMVC project using Eclipse
In the foreground html, the enctype of form is multipart/form-data. Note that the name of input and select should correspond to the members in StudentForm one by one.
The uploaded url is addAction.do. The parameters of this action method use StudentForm to map the submitted data. At this time, the data of the submitted file can be obtained. Then we operate on the file.
Create a PHOTO_TBL table: The PHOTO_DATA field is used to store files, and the type is MyBatis longblob; then write the Mapper's Java interface PhotoMapper: including additions, deletions, modifications and searches; mappper's xml file: SQL statements corresponding to the JAVA interface.
And the Spring configuration file needs to add a bean declaration.
Below are the code snippets of html, action, and StudentForm; create the sql, PhotoMapper.java interface code, and PhotoMapper.xml file code of the PHOTO_TBL table.
1.1 HTML form writing method
1.<form action="<c:url value='addAction.do' />" method="post" enctype="multipart/form-data"> 2. <table> 3. <tr> 4. <td align="right">Photo:</td> 5. <td><input type="file" name="studentPhoto"/> 6. </tr> 7. </table> 8. <input type="submit"> 9.</form>
1.2 action method
1./** 2. * Added - Submit 3. */ 4.@RequestMapping(value = "addAction.do") 5.public String add_action(ModelMap model, StudentForm form) { 6. 7.} 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; 10. private MultipartFile studentPhoto; 11. 12.} 1.4 Create PHOTO_TBL
1.CREATE TABLE PHOTO_TBL 2.( 3. PHOTO_ID VARCHAR(100) PRIMARY KEY, 4. PHOTO_DATA LONGBLOB, 5. FILE_NAME VARCHAR(10) 6.);
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); 10. 11. public PhotoEntity getPhotoEntityByPhotoId(String photoId); 12. 13.} 1.6 PhotoMapper.xml file
Including addition, deletion, modification and search. The newly added photoId uses the mysql custom function to automatically generate primary keys. When operating blobs, you need to set the typeHandler to "org.apache.ibatis.type.BlobTypeHandler. The parameters need to be specified later when insert and update, and they need to be specified in 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. 10. <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, 16. FILE_NAME) 17. VALUES(#{photoId, jdbcType=VARCHAR}, 18. #{photoData, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler}, 19. #{fileName, jdbcType=VARCHAR}) 20. </insert> 21. 22. <delete id="deletePhotoByPhotoId"> 23. DELETE FROM PHOTO_TBL 24. WHERE PHOTO_ID = #{photoId, jdbcType=VARCHAR} 25. </delete> 26. 27. <update id="updatephotoData" > 28. UPDATE PHOTO_TBL 29. SET PHOTO_DATA = #{photoData, javaType=byte[], jdbcType=BLOB, typeHandler=org.apache.ibatis.type.BlobTypeHandler}, 30. FILE_NAME = #{fileName, jdbcType=VARCHAR} 31. WHERE PHOTO_ID = #{photoId, jdbcType=VARCHAR} 32. </update> 33. 34. <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
The Spring configuration file needs to add a declaration of org.springframework.web.multipart.commons.CommonsMultipartResolver.
1.<bean id="multipartResolver"> 2. <property name="maxUploadSize" value="1073741824" /> 3.</bean>
2. Put the file on the server
1.private static final String uploadFilePath = "d://temp_upload_file//"; 2. 3./** 4. * New - Submit only saves files to the server 5. */ 6.@RequestMapping(value = "addAction.do") 7.public String add_action(ModelMap model, StudentForm form) { 8.try { 9. MultipartFile uploadFile = form.getStudentPhoto(); 10. String filename = uploadFile.getOriginalFilename(); 11. InputStream is = uploadFile.getInputStream(); 12. // If the server already has a file with the same name as the upload file, the prompt message is output 13. File tempFile = new File(uploadFilePath + filename); 14. if (tempFile.exists()) { 15. boolean delResult = tempFile.delete(); 16. System.out.println("Delete existing files: " + delResult); 17. } 18. // Start saving files to the server 19. if (!filename.equals("")) { 20. FileOutputStream fos = new FileOutputStream(uploadFilePath + filename); 21. byte[] buffer = new byte[8192]; // Read 8K bytes each time 22. int count = 0; 23. // Start reading the bytes of the uploaded file and output it to the server uploaded file output stream 24. while ((count = is.read(buffer)) > 0) { 25. fos.write(buffer, 0, count); // Write byte stream to the server file 26. } 27. fos.close(); // Close FileOutputStream object 28. is.close(); // InputStream object 29. } 30. } catch (FileNotFoundException e) { 31. e.printStackTrace(); 32. } catch (IOException e) { 33. e.printStackTrace(); 34. } 35.} 3. Upload the file to the database
1./** 2. * New - Submit and 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(); 10. PhotoEntity photoEntity = new PhotoEntity(); 11. photoEntity.setPhotoData(studentPhotoData); 12. photoEntity.setFileName(fileName); 13. this.photoMapper.createPhoto(photoEntity); 14.} 4. Download the file
To download the file, you need to restore the byte array to a file.
First, use mybatis to find out the byte array in the database and specify the file name (including format). Then use OutputStream to enter the file
1.@RequestMapping(value = "downPhotoById") 2.public void downPhotoByStudentId(String id, final HttpServletResponse response){ 3. PhotoEntity entity = this.photoMapper.getPhotoEntityByPhotoId(id); 4. byte[] data = entity.getPhotoData(); 5. String fileName = entity.getFileName()== null ? "Photo.png" : entity.getFileName(); 6. fileName = URLEncoder.encode(fileName, "UTF-8"); 7. response.reset(); 8. response.setHeader("Content-Disposition", "attachment; filename=/"" + fileName + "/""); 9. response.addHeader("Content-Length", "" + data.length); 10. response.setContentType("application/octet-stream;charset=UTF-8"); 11. OutputStream outputStream = new BufferedOutputStream(response.getOutputStream()); 12. outputStream.write(data); 13. outputStream.flush(); 14. outputStream.close(); 15.}<a href="<%=request.getContextPath() %>/downPhotoById.do?id=8000001">Download Photos</a>
5. Display byte image 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; 10. byte[] buf = new byte[1024]; 11. while ((len = in.read(buf, 0, 1024)) != -1) { 12. outputSream.write(buf, 0, len); 13. } 14. outputSream.close(); 15.}<img src="<%=request.getContextPath() %>/getPhotoById.do?id=8000001"/>
6. Scale the picture by length and width equal proportions
1.@RequestMapping(value = "getPhotoId") 2.public void getPhotoById (String id, int width, int height, final HttpServletResponse 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"); 10. OutputStream outputSream = response.getOutputStream(); 11. InputStream in = new ByteArrayInputStream(data); 12. int len = 0; 13. byte[] buf = new byte[1024]; 14. while ((len = in.read(buf, 0, 1024)) != -1) { 15. 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)); 22. int imageOldWidth = buffered_oldImage.getWidth(); 23. int imageOldHeight = buffered_oldImage.getHeight(); 24. double scale_x = (double) width / imageOldWidth; 25. double scale_y = (double) height / imageOldHeight; 26. double scale_xy = Math.min(scale_x, scale_y); 27. int imageNewWidth = (int) (imageOldWidth * scale_xy); 28. int imageNewHeight = (int) (imageOldHeight * scale_xy); 29. BufferedImage buffered_newImage = new BufferedImage(imageNewWidth, imageNewHeight, BufferedImage.TYPE_INT_RGB); 30. buffered_newImage.getGraphics().drawImage(buffered_oldImage.getScaledInstance(imageNewWidth, imageNewHeight, BufferedImage.SCALE_SMOOTH), 0, 0, null); 31. buffered_newImage.getGraphics().dispose(); 32. ByteArrayOutputStream outPutStream = new ByteArrayOutputStream(); 33. ImageIO.write(buffered_newImage, "jpeg", outPutStream); 34. return outPutStream.toByteArray(); 35.}<img src="<%=request.getContextPath() %>/getPhotoById.do?id=8000001&width=300&height=300"/>
The above is the combination of MyBatis and SpringMVC to implement file upload and download functions. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!