SpringMVC 文件上传

Spring MVC

  • maven

    commons-fileupload
    commons-fileupload
    1.3.3

  • spring配置

    
        
        
        
    

    
    
  • 编码

前端

controller

@PostMapping(value = {"doUpload"})
    @ResponseBody
    public String upload(@RequestParam("uploadFile") MultipartFile file) throws IOException {
        logger.info(file.getOriginalFilename());
        if (!file.isEmpty()) {

            try {
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File(CommonsInfo.UPDATE_PATH, file.getOriginalFilename()));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "success";
        }
        return "fail";
    }

aop

@Aspect
public class FileAop {

    private Logger logger = Logger.getLogger(FileAop.class);

    @Pointcut("execution(* org.yiva.exam.controller.FileController.upload(..))")
    public void poincutFile(){

    }

    /**
    *  在访问上传文件功能前判断是否已经存在上传文件的保存目录,如没有则新建
    */
    @Before(value = "poincutFile()")
    public void before(JoinPoint joinPoint) throws IOException {
        File folder = new File(CommonsInfo.UPDATE_PATH);
        if (!folder.isDirectory() || !folder.exists()) {
            folder.mkdirs();
            logger.info("create Directory updateFile");
        }
    }

}

你可能感兴趣的:(SpringMVC 文件上传)