springboot 文件上傳下載(簡潔明瞭)

1.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <meta charset="UTF-8"/>
    <title>Insert title here</title>
</head>
<body>
<h1 th:inlines="text">文件上傳</h1>
<form action="fileUpload" method="post" enctype="multipart/form-data">
    接受路徑:<input type="text" name="path">
    <p>選擇文件: <input type="file" name="fileName"/></p>
    <p><input type="submit" value="提交"/></p>
</form>
<h1 th:inlines="text">文件下載</h1>
<form action="download" method="post">
    文件名稱:<input type="text" name="filename">
    文件目錄:<input type="text" name="filePath">
    <input type="submit" value="下載">
</form>
</body>
</html>

2.controller

package com.knowology.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @ProjectName: upload
 * @Package: com.example.upload.controler
 * @ClassName: FileUploadController
 * @Author: 韓惠德
 * @Description:
 * @Date: 2020/2/19 10:30
 * @Version: 1.0
 */
@Controller
public class FileUploadController {

    /*
     * 獲取file.html頁面
     */
    @RequestMapping("file")
    public String file() {
        return "file";
    }

    /**
     * 實現文件上傳
     */
    @RequestMapping("fileUpload")
    @ResponseBody
    public String fileUpload(@RequestParam("fileName") MultipartFile file, @RequestParam("path") String path) {
        if (file.isEmpty()) {
            return "false";
        }
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        System.out.println(fileName + "-->" + size);
        File dest = new File(path + "/" + fileName);
        if (!dest.getParentFile().exists()) { //判斷文件父目錄是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
            return "true";
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "false";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "false";
        }
    }

    @RequestMapping("multifile")
    public String multifile() {
        return "/multifile";
    }
    @RequestMapping("download")
    public void download(HttpServletResponse response, String filename, String filePath) throws Exception {
        // 文件地址,真實環境是存放在數據庫中的
        File file = new File(filePath + "/" + filename);        // 穿件輸入對象
        FileInputStream fis = new FileInputStream(file);
        // 設置相關格式
        response.setContentType("application/force-download");
        // 設置下載後的文件名以及header
        response.addHeader("Content-disposition", "attachment;fileName=" + filename);
        // 創建輸出對象
        OutputStream os = response.getOutputStream();
        // 常規操作
        byte[] buf = new byte[1024];
        int len = 0;
        while((len = fis.read(buf)) != -1) {
            os.write(buf, 0, len);
        }
        fis.close();
    }

}

3.config

package com.knowology.config;

import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;

import javax.servlet.MultipartConfigElement;

/**
 * @ProjectName: upload
 * @Package: com.example.upload.config
 * @ClassName: FileConfig
 * @Author: 韓惠德
 * @Description:
 * @Date: 2020/2/19 10:35
 * @Version: 1.0
 */
@Configuration
public class FileConfig {
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();

        //單個文件最大
        factory.setMaxFileSize(DataSize.ofMegabytes(500)); //KB,MB
        /// 設置總上傳數據總大小
        factory.setMaxRequestSize(DataSize.ofMegabytes(500));
        return factory.createMultipartConfig();
    }
}

4.pom

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

5.yml

multipart:
  maxRequestSize: 500Mb
  maxFileSize: 500Mb
spring:
  thymeleaf:
    mode: HTML5
    cache: false
    prefix: classpath:/templates/
    servlet:
      content-type: text/html
    encoding: UTF-8
    suffix: .html

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章