1. 程式人生 > >spring boot + axios 上傳檔案

spring boot + axios 上傳檔案

背景

純新手記錄一下springboot 上傳檔案。(以前是做.net 的)

後端實現


  • FileUtil
用來儲存檔案建立資料夾。
 public static void save (byte[] file,String filePath, String fileName) throws  Exception{
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        if
(filePath.endsWith(File.separator)){ filePath=filePath.substring(0,filePath.length()-2); } FileOutputStream out = new FileOutputStream(filePath+File.separator+fileName); out.write(file); out.flush(); out.close(); }

  • FileControl
用來接收伺服器傳過來檔案
@Controller
@RequestMapping("/${cubeboot.app-file-path}/file")
public class FileController {

    @Autowired
    private CubeBootProperties properties;

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public AppResponse upload (@RequestParam("file") MultipartFile file, HttpServletRequest request) throws
Exception{ String contentType = file.getContentType(); String fileName = file.getOriginalFilename(); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMhh"); String profixTime = sdf1.format(new Date()); String absolutePath=properties.getFileUploadPath()+ File.separator+profixTime; String fileExtension= FileUtil.getExtensionNameByName(fileName); String randomName= UUID.randomUUID().toString().replace("-","").substring(0,8)+fileExtension; FileUtil.save(file.getBytes(),absolutePath,randomName); String realtivePath="/upload/"+profixTime+"/"+randomName; return new AppResponse(true,realtivePath); } }

  • WebMvcConfigurerAdapter 複寫
實現資源指向
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**").addResourceLocations("file:///"+cubeBootProperties.getFileUploadPath()); //file:///可以指向你你儲存檔案的任何地址
}

  • 前端js
axios 上傳
    change(e) {
      if (e.target.files.length === 0) return
      const file = e.target.files[0]
      const param = new FormData()
      param.append('file', file)

      const config = {
        headers: { 'Content-Type': 'multipart/form-data' }
      }
      axios.post(this.action, param, config).then(e => {       
        // 處理
      })
    }

感想

初來java 真是撞的鼻青臉腫。

廣告 :想學架構的同學看下 直通車