Springboot文件上傳與下載


一、創建簡單的springboot-web項目

二、文件上傳屬性配置

#默認支持文件上傳
spring.http.multipart.enabled =true
spring.http.multipart.file-size-threshold =0
# 上傳文件的臨時目錄
#spring.http.multipart.location=E:/upload/temp/
# 最大支持文件大小
spring.http.multipart.max-file-size =100MB
# 最大支持請求大小
spring.http.multipart.max-request-size =100Mb

三、文件上傳代碼

1.Controller層代碼:

@RestController
public class UploadController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

    @GetMapping("/toUpload")
    public String upload() {
        return "upload";
    }

    @PostMapping("/upload")
    public String UploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "請選擇文件";
        }
   //獲取文件名
        String fileName = file.getOriginalFilename();
        String filePath = "C:/Users/upload/";
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            LOGGER.info("上傳成功");
            return "上傳成功";
        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
        }
        return "上傳失敗!";
    }
}

2.jsp代碼

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <title>單文件上傳</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

四、文件下載代碼

@RequestMapping(value = "/download", method = RequestMethod.GET)
    @ResponseBody
    public String testDownload(HttpServletResponse res,HttpServletRequest request) {
        String fileName = "xxx.txt";
        String filePath = "D:/uploadFile";
        File file = new File(filePath + "/" + fileName);
        System.out.println(file);
        if (file.exists()){//判斷文件是否存在
            //判斷瀏覽器是否為火狐
            try {
                if ("FF".equals(getBrowser(request))) {
                    // 火狐瀏覽器 設置編碼new String(realName.getBytes("GB2312"), "ISO-8859-1");
                    fileName = new String(fileName.getBytes("GB2312"), "ISO-8859-1");
                }else{
                    fileName = URLEncoder.encode(fileName, "UTF-8");//encode編碼UTF-8 解決大多數中文亂碼
                    fileName = fileName.replace("+", "%20");//encode后替換空格  解決空格問題
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            res.setContentType("application/force-download");//設置強制下載
            res.setHeader("Content-Disposition", "attachment;filename=" + fileName);//設置文件名
            byte[] buff = new byte[1024];// 用來存儲每次讀取到的字節數組
            //創建輸入流(讀文件)輸出流(寫文件)
            BufferedInputStream bis = null;
            OutputStream os = null;
            try {
                os = res.getOutputStream();
                bis = new BufferedInputStream(new FileInputStream(file));
                int i = bis.read(buff);
                while (i != -1) {
                    os.write(buff, 0, buff.length);
                    os.flush();
                    i = bis.read(buff);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (os != null){
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }else {
            return "文件不存在!!!";
        }
        return "download success";
    }
 
    /**
     * @Title: getBrowser
     * @Description: 判斷客戶端瀏覽器
     * @return String
     * @author
     * @date
     */
    private static String getBrowser(HttpServletRequest request) {
        String UserAgent = request.getHeader("USER-AGENT").toLowerCase();
        if (UserAgent != null) {
            if (UserAgent.indexOf("msie") != -1)
                return "IE";
            if (UserAgent.indexOf("firefox") != -1)
                return "FF";
            if (UserAgent.indexOf("safari") != -1)
                return "SF";
        }
        return null;
    }
}

五、測試

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM