springboot+web文件上传和下载
Posted 嗨_放飞梦想
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot+web文件上传和下载相关的知识,希望对你有一定的参考价值。
一、首先安装mysql数据库,开启web服务器。
二、pom.xml文件依赖包配置如下:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.weChat</groupId> <artifactId>SmallProject</artifactId> <version>0.0.1-SNAPSHOT</version> <name>SmallProject</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
二、使用IDE建立springboot+web工程,连接数据库的application.properties配置如下:
1 #服务器端口设置 2 server.port=8080 3 #必须包含项目名称 4 #server.servlet.context-path=/demo 5 #数据库配置信息 6 spring.datasource.driver-class-name=com.mysql.jdbc.Driver 7 spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false 8 spring.datasource.username=root 9 spring.datasource.password=****** 10 #设置单个上传文件的大小 11 spring.servlet.multipart.max-file-size=200GB 12 #设置一次请求上传文件的总量 13 spring.servlet.multipart.max-request-size=200GB 14 spring.jpa.hibernate.ddl-auto=update 15 spring.jpa.show-sql=true
三、建立数据库表格的Test.java内容如下:
1 package com.wechat.smallproject.dataBaseTable; 2 3 import javax.persistence.Column; 4 import javax.persistence.Entity; 5 import javax.persistence.Id; 6 import javax.persistence.Table; 7 import java.util.Date; 8 9 /** 10 * @Author CFF 11 * @Date:Created in 16:25 2019/1/10 12 */ 13 @Table(name = "picture_info") 14 @Entity 15 public class Test { 16 @Id 17 /** 18 * 主键ID 19 */ 20 @Column(length = 32) 21 private Integer Id; 22 /** 23 * 图片名称 24 */ 25 private String pictureName; 26 /** 27 * 图片格式 28 */ 29 private String pictureFormat; 30 /** 31 * 图片上传存放地址 32 */ 33 private String picturePath; 34 /** 35 * 图片上传大小 36 */ 37 private long pictureSize; 38 /** 39 * 上传图片时间 40 */ 41 private Date uploadPictureTime; 42 43 public Integer getId() { 44 return Id; 45 } 46 47 public void setId(Integer id) { 48 Id = id; 49 } 50 51 public String getPictureName() { 52 return pictureName; 53 } 54 55 public void setPictureName(String pictureName) { 56 this.pictureName = pictureName; 57 } 58 59 public String getPictureFormat() { 60 return pictureFormat; 61 } 62 63 public void setPictureFormat(String pictureFormat) { 64 this.pictureFormat = pictureFormat; 65 } 66 67 public String getPicturePath() { 68 return picturePath; 69 } 70 71 public void setPicturePath(String picturePath) { 72 this.picturePath = picturePath; 73 } 74 75 public long getPictureSize() { 76 return pictureSize; 77 } 78 79 public void setPictureSize(long pictureSize) { 80 this.pictureSize = pictureSize; 81 } 82 83 public Date getUploadPictureTime() { 84 return uploadPictureTime; 85 } 86 87 public void setUploadPictureTime(Date uploadPictureTime) { 88 this.uploadPictureTime = uploadPictureTime; 89 } 90 91 }
四、建立TestDao.java接口,用来保存数据库表信息:
1 package com.wechat.smallproject.dao; 2 3 import com.wechat.smallproject.dataBaseTable.Test; 4 import org.springframework.data.jpa.repository.JpaRepository; 5 6 /** 7 * @Author CFF 8 * @Date:Created in 16:45 2019/1/10 9 */ 10 public interface TestDao extends JpaRepository<Test,Integer> { 11 }
五、建立TestController.java,编写文件上传和下载方法。
1 package com.wechat.smallproject.controller; 2 3 import com.wechat.smallproject.dao.TestDao; 4 import com.wechat.smallproject.dataBaseTable.Test; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.web.bind.annotation.*; 7 import org.springframework.web.multipart.MultipartFile; 8 import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest; 9 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 import java.io.*; 13 import java.text.SimpleDateFormat; 14 import java.util.*; 15 16 /** 17 * @Author CFF 18 * @Date:Created in 16:47 2019/1/10 19 */ 20 @RestController 21 public class TestController { 22 @Autowired 23 TestDao testDao; 24 25 public String pictureName=null ; 26 public String picturePath=null ; 27 28 @RequestMapping(value = "/upload") 29 public void uploadPicture(HttpServletRequest request) throws Exception { 30 //获取文件需要上传到的路径 31 picturePath = "C:\Users\CFF\Desktop\Project\PicturesPath\"; 32 33 // 判断存放上传文件的目录是否存在(不存在则创建) 34 File dir = new File(picturePath); 35 if (!dir.exists()) { 36 dir.mkdir(); 37 } 38 try { 39 StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request; 40 //获取formdata的值 41 Iterator<String> iterator = req.getFileNames(); 42 while (iterator.hasNext()) { 43 MultipartFile file=req.getFile(iterator.next()); 44 //获取文件后缀名 45 String fileSuffixName=file.getOriginalFilename().substring(86); 46 //真正写到磁盘上 47 //全球唯一id 48 String uuid= UUID.randomUUID().toString().replace("-",""); 49 pictureName=uuid+fileSuffixName; 50 //将文件信息存入数据库中 51 Test test =new Test(); 52 if(new Date().hashCode()<0){ 53 test.setId(-new Date().hashCode()); 54 } 55 else{ 56 test.setId(new Date().hashCode()); 57 } 58 test.setUploadPictureTime(new Date()); 59 test.setPictureName(uuid); 60 test.setPicturePath(picturePath+pictureName); 61 test.setPictureSize(file.getSize()); 62 test.setPictureFormat(file.getContentType()); 63 testDao.save(test); 64 65 File file1=new File(picturePath+pictureName); 66 OutputStream out=new FileOutputStream(file1); 67 out.write(file.getBytes()); 68 out.close(); 69 System.out.println("图片上传成功!"); 70 } 71 } catch (Exception e) { 72 System.out.println(e); 73 } 74 } 75 //文件下载相关代码 76 @RequestMapping("/download") 77 public void fileDownload( HttpServletResponse response){ 78 File file = new File(picturePath+pictureName); 79 if (pictureName != null) { 80 if (file.exists()) { 81 response.setContentType("application/force-download");// 设置强制下载不打开 82 Date currentTime = new Date(); 83 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); 84 String dataTime=dateFormat.format(currentTime); 85 //文件重新命名 86 String pictureNewName = dataTime+pictureName.substring(pictureName.indexOf(".")); 87 response.addHeader("Content-Disposition", 88 "attachment;fileName=" + pictureNewName);// 设置文件名 89 byte[] buffer = new byte[1024]; 90 FileInputStream fis = null; 91 BufferedInputStream bis = null; 92 try { 93 fis = new FileInputStream(file); 94 bis = new BufferedInputStream(fis); 95 OutputStream os = response.getOutputStream(); 96 int i = bis.read(buffer); 97 while (i != -1) { 98 os.write(buffer, 0, i); 99 i = bis.read(buffer); 100 } 101 System.out.println(pictureNewName+"下载成功!!!"); 102 } catch (Exception e) { 103 e.printStackTrace(); 104 System.out.println(pictureNewName+"下载失败!!!"+e); 105 } finally { 106 if (bis != null) { 107 try { 108 bis.close(); 109 } catch (IOException e) { 110 e.printStackTrace(); 111 } 112 } 113 if (fis != null) { 114 try { 115 fis.close(); 116 } catch (IOException e) { 117 e.printStackTrace(); 118 } 119 } 120 } 121 } 122 } 123 } 124 }
六、upload.html如下:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <title>上传图片</title> 5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 6 </head> 7 <body> 8 <form action="/upload" method="post" enctype="multipart/form-data"> 9 文件:<input type="file" name="filename"/> 10 <input type="submit" value="提交"/> 11 </form> 12 <a href="/download">下载</a> 13 </body> 14 </html>
以上是关于springboot+web文件上传和下载的主要内容,如果未能解决你的问题,请参考以下文章