1. 程式人生 > >複習之SpringBoot應用(一)——SpringBoot檔案上傳

複習之SpringBoot應用(一)——SpringBoot檔案上傳

檔案上傳可以說開發人員的基本技能

SpringBoot專案結構與ssm有很大區別,檔案上傳也有差異

  • 頁面
<!DOCTYPE html>
<html>
<head>
    <title>檔案上傳示例</title>
</head>
<body>
<h2>檔案上傳示例</h2>
<hr/>
<form method="POST" enctype="multipart/form-data" action="/recruit/upload">
    <p>
        檔案:<input type="file" name="img" />
    </p>
    <p>
        <input type="submit" value="上傳" />
    </p>
</form>
</body>
</html>
  • 後臺檔案上傳處理 檔案上傳一般在Controller實現 FileUploadController檔案
 	//spring boot 實現上傳圖片
    @PostMapping("upload")
    @ResponseBody
    public String upload(@RequestParam("img") MultipartFile img,  HttpServletResponse response) throws IOException {
        String result=null;
        response.setHeader("content-type","text/html;charset=UTF-8");
        if (!img.isEmpty()) {
            // 獲取檔名
            String fileName = img.getOriginalFilename();
            //生成隨機檔名
            String name =UUID.randomUUID().toString().replaceAll("-", "");
            // 獲取檔案的字尾名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            log.info("上傳的檔案字尾名為:" + suffixName);
            //判斷檔案的型別是否為指定的檔案型別
            if (!filterType(img.getContentType())) {
                result = "error:" + img.getContentType()+ " type not upload file type";
            }else {
                try {
                    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File("D://upload/" + name+suffixName)));
                    out.write(img.getBytes());
                    out.flush();
                    out.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    result = "upload file failed !";
                } catch (IOException e) {
                    e.printStackTrace();
                    result = "upload file failed !";
                }
                result = "upload file success !";
            }
        }else{
            result="upload file failed !";
        }
      return result;
    }
    
     /**
     * 指定的上傳型別   zip 和   圖片格式的檔案
     */
    private static final String[] types = { "application/x-zip-compressed",
            "ZIP", "image/pjpeg","image/x-png","image/jpeg","image/jpg" ,"image/JPG","image/png","image/PNG"};  //"application/octet-stream; charset=utf-8",

    /***
     * 判斷檔案的型別是否為指定的檔案型別
     * @return
     */
    public boolean filterType(String imgType) {
        boolean isFileType = false;
        for (String type : types) {
            if (type.equals(imgType)) {
                isFileType = true;
                break;
            }
        }
        return isFileType;
    }
  • 配置Bean來設定檔案大小
@Configuration
public class FileUploadConfiguration {
    @Bean
    public MultipartConfigElement multipartConfigElement(){
        MultipartConfigFactory factory =new MultipartConfigFactory();
        //檔案大小
        factory.setMaxFileSize("2MB");
        //檔案存放臨時資料夾
        factory.setLocation("C://TEMP/");
        return  factory.createMultipartConfig();
    }
}

執行結果:成功! 在這裡插入圖片描述