1. 程式人生 > >springboot2.0 檔案上傳下載

springboot2.0 檔案上傳下載

頁面

 <h2>上傳檔案sss</h2>
    <form action="/file/upload" method="post" enctype="multipart/form-data" >
        <!--<input  type="file" name="myfile" method="post" action="localfile/upload"/><br>-->
        <!--<input type="submit" value="提交"/>-->

        <input type="file" name="myfile"/><br/>
        <input  type="submit" value="提交"/>

    </form>
    <h1>檔案下載</h1>
    <a href="/file/download">下載</a>

controller:

package com.springboot2.thyemleaf.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.*;
import java.util.UUID;

/**
 * Created by  lpw'ASUS on 2018/5/30.
 */
@Controller
@RequestMapping("/file")
public class MyfileCOntroller {

    @RequestMapping("upload")
    @ResponseBody
    public String getfile(@RequestParam("myfile") MultipartFile file){
        System.out.println("file name = "+file.getOriginalFilename());

        // 獲取檔名
        String fileName = file.getOriginalFilename();
        // 獲取字尾
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 檔案上產的路徑
        String filePath = "d:/upload/";
        // fileName處理
        fileName = filePath+ UUID.randomUUID()+fileName;
        // 檔案物件
        File dest = new File(fileName);
        // 建立路徑
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }

        try {
            //儲存檔案
            file.transferTo(dest);
            return "上傳成功";
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "上傳失敗";
    }

    @RequestMapping("download")
    public void download(HttpServletResponse response) throws FileNotFoundException {
        File file =new File("C:\\Users\\ASUS\\Desktop\\spring-boot-reference.pdf");
        FileInputStream fileInputStream=new FileInputStream(file);
        // 設定被下載而不是被開啟
        response.setContentType("application/gorce-download");
        // 設定被第三方工具開啟,設定下載的檔名
        response.addHeader("Content-disposition","attachment;fileName=spring-boot-reference.pdf");
        try {
            OutputStream outputStream = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

設定上傳的大小

application.properties

#最大檔案大小。值可以使用字尾“MB”或“KB”。指示兆位元組或千位元組大小。
spring.servlet.multipart.max-file-size=10MB
# 最大請求大小可以是mb也可以是kb
spring.servlet.multipart.max-request-size=10MB