SpringBoot 上傳文件功能


 

 

注意事項:

   springboot默認有以下文件配置要求, 可以自行在配置文件里面修改


spring:
servlet:
multipart:
enabled: true #是否處理上傳
max-file-size: 1MB #允許最大的單個上傳大小,單位可以是kb
max-request-size: 10MB #允許最大請求大小

 

 

 

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

@Controller
public class FileUploadController {


    /**
     * 因為最終項目會打成jar包,所以這個的路徑不能是jar包里面的路徑
     * 可以使用其他路徑,比如上傳到F盤下的upload文件夾下 寫成:F:/upload/
     */
    private String fileUploadPath = "";

    /**
     * 文件上傳,具體邏輯可以自行完善
     *
     * @param file 前端表單的name名
     * @return w
     */
    @PostMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file) {

        if (file.isEmpty()) {
            //文件空了
            return null;
        }

        //文件擴展名
        String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        //使用UUID生成文件名稱
        String fileName = UUID.randomUUID().toString() + extName;

        //文件上傳的全路徑
        String filePath = fileUploadPath + fileName;

        File toFile=new File(filePath);

        if (!toFile.getParentFile().exists()){
            //文件夾不存在,先創建文件夾
            toFile.getParentFile().mkdirs();
        }
        try {
            //進行文件復制上傳
            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(toFile));
        } catch (Exception e) {
            //上傳失敗
            e.printStackTrace();
        }
        //返回文件所在絕對路徑
        return filePath;

    }

}

 

 

然后添加個配置就可以把路徑映射出去

@Configuration
public class webMvcConfigurerAdapter implements WebMvcConfigurer {
    /**
     * 配置靜態訪問資源
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/file/**").addResourceLocations("classpath:/path/");
    }
}

 

  • addResoureHandler:指的是對外暴露的訪問路徑
  • addResourceLocations:指的是內部文件放置的目錄(如果在項目下 可以配置成    file:/path/)

 


免責聲明!

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



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