1. 程式人生 > >springboot+web文件上傳和下載

springboot+web文件上傳和下載

文件上傳和下載 ioe down spring spa web工程 d+ ffi http

一、首先安裝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文件上傳和下載