1. 程式人生 > >Springboot上傳與下載檔案

Springboot上傳與下載檔案

  • application.yml
  #設定靜態資源路徑
  resources:
    static-locations: classpath:static/,file:static/
    #檔案大小
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB
  • Springboot上傳檔案(單個檔案)

           uploadImg.html檔案:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="keywords" content="keyword1,keyword2,keyword3"/>
    <meta name="description" content="this is my page"/>
    <meta name="content-type" content="text/html; charset=UTF-8"/>
    <title>Title</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="/uploadImg">
    檔案:<input type="file" name="file"/>
    <input type="submit" value="上傳"/>
</form>
</body>
</html>

     UploadImgController檔案: 

 /**
     * 上傳單個檔案
     * @param file
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadImg")
    @ResponseBody
    public String uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request)throws Exception{
        if(file.isEmpty()){
            return "請選擇檔案上傳";
        }
       String contentType = file.getContentType();
       String fileName = file.getOriginalFilename();
//        String filePath = "D:\\fileupload\\";//固定儲存路徑
     //  String filePath = request.getSession().getServletContext().getRealPath("/imgupload");
       //log.info("filepath="+ClassUtils.getDefaultClassLoader().getResource("").getPath());//輸出: F:/tonglingling/springbootDemo1/target/classes/

        try {
            File path=new File(ResourceUtils.getURL("classpath:").getPath());
            File targetFile=new File(path.getAbsolutePath(),"static/fileupload/");//jar包下面的target目錄
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            log.info("targer="+targetFile); // F:\tonglingling\springbootDemo1\target\classes\static\fileupload
            FileOutputStream out = new FileOutputStream(targetFile+"/"+fileName);
            out.write(file.getBytes());
            out.flush();
            out.close();
         //   FileUtil.uploadFile(file.getBytes(),filePath,fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "uploadImg Success";
    }

 

  • Springboot上傳檔案(多個檔案)
  •  /**
         * 批量上傳圖片
         * @param request
         * @return
         */
        @PostMapping("/batchImg")
        @ResponseBody
        public String batchImg(HttpServletRequest request){
            List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("file");
            MultipartFile file = null;
            BufferedOutputStream stream = null;
            for(int i=0;i<files.size();i++){
                file = files.get(i);
                if(!file.isEmpty()){
                    try {
                        String fileName = file.getOriginalFilename();
                        File path=new File(ResourceUtils.getURL("classpath:").getPath());
                        File targetFile=new File(path.getAbsolutePath(),"static/imgupload/");//jar包下面的target目錄
                        if(!targetFile.exists()){
                            targetFile.mkdirs();
                        }
                        byte[] bytes = file.getBytes();
                        stream = new BufferedOutputStream(new FileOutputStream(new File(targetFile+"/"+fileName)));
                        stream.write(bytes);
                        stream.close();
                    } catch (IOException e) {
                        stream = null;
                        e.printStackTrace();
                        return "上傳失敗"+i+"=>"+e.getMessage();
                    }
                }else{
                    return "檔案為空";
                }
            }
            return "上傳成功";
        }

     

  • Springboot下載檔案
   /**
     * 下載檔案
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @GetMapping("/download")
    @ResponseBody
    public String download(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String fileName = "2.jpg";// 檔名
        if (fileName != null) {
            //設定檔案路徑
        //    String pathname = "D:\\fileupload\\1.jpg";
            File path=new File(ResourceUtils.getURL("classpath:").getPath());
            File targetFile=new File(path.getAbsolutePath(),"static/imgupload/");//jar包下面的target目錄
            File file = new File(targetFile+"/"+fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 設定強制下載不開啟
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 設定檔名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下載成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    bis.close();
                    fis.close();
                }
            }else{
                return "檔案不存在";
            }
        }
        return "下載失敗";
    }