1. 程式人生 > 實用技巧 >springboot檔案上傳

springboot檔案上傳

1.pom檔案中引入需要的依賴

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId
> <version>1.3.2</version> </dependency>

2.編寫可控制類-單檔案上傳

//單檔案上傳
    @RequestMapping("/fileupload")
    @ResponseBody
    public String fileload(MultipartFile fileupload) throws IOException {//獲取檔案的原始名稱
        String oldName=fileupload.getOriginalFilename();
        //獲取原始檔案的字尾
        String extension= "."+FilenameUtils.getExtension(oldName);
        
//生成新的檔名稱 String newFileName=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ UUID.randomUUID().toString().replace("-", "")+extension; //檔案大小 Long size=fileupload.getSize(); //檔案的型別 String fileType = fileupload.getContentType(); //生成日期格式的目錄 接收到的檔案放在static下面的files中
String realpath= ResourceUtils.getURL("classpath:").getPath()+"static/files"; //在files中動態的建立資料夾 String dateDirpath=realpath+"/"+new SimpleDateFormat("yyyy-MM-dd").format(new Date()); File datedir=new File(dateDirpath); if(!datedir.exists()){ datedir.mkdirs(); } //處理檔案上傳 fileupload.transferTo(new File(datedir,newFileName)); return "success"; }

3.多檔案上傳

//多檔案上傳
    @RequestMapping("/morefileload")
    @ResponseBody
    public String fileload(MultipartFile[] fileupload) throws IOException {
        for (MultipartFile multipartFile : fileupload) {
            //獲取檔案的原始名稱
            String oldName=multipartFile.getOriginalFilename();
            //獲取原始檔案的字尾
            String extension= "."+FilenameUtils.getExtension(oldName);
            //生成新的檔名稱
            String newFileName=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ UUID.randomUUID().toString().replace("-", "")+extension;
            //檔案大小
            Long size=multipartFile.getSize();
            //檔案的型別
            String fileType = multipartFile.getContentType();
            //生成日期格式的目錄  接收到的檔案放在static下面的files中
            String realpath= ResourceUtils.getURL("classpath:").getPath()+"static/files";
            //在files中動態的建立資料夾
            String dateDirpath=realpath+"/"+new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            File datedir=new File(dateDirpath);
            if(!datedir.exists()){
                datedir.mkdirs();
            }
            //處理檔案上傳
            multipartFile.transferTo(new File(datedir,newFileName));
        }

        return "success";
}

學習工作之餘記錄一下 如有雷同純屬巧合