SpringBoot 文件上传

首先,创建一个index.html页面




    
    Title


然后,在Controller中新建文件上传方法

package com.example.demo.controller;

        import org.springframework.web.bind.annotation.PostMapping;
        import org.springframework.web.bind.annotation.RestController;
        import org.springframework.web.multipart.MultipartFile;
        import javax.servlet.http.HttpServletRequest;
        import java.io.File;
        import java.io.IOException;
        import java.text.SimpleDateFormat;
        import java.util.Date;
        import java.util.UUID;


@RestController
public class TestController {
  SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");//根据日期创建文件分级目录

  @PostMapping("/upload")
  public void upload(MultipartFile file,HttpServletRequest req) throws IOException {
    String format = sdf.format(new Date());
    String realPath = req.getServletContext().getRealPath("/img")+ format;//我们即将要保存的位置
    System.out.println(realPath);
    File folder = new File(realPath);
    if(!folder.exists()){//判断是否存在文件
      folder.mkdirs();
    }
    String oldName = file.getOriginalFilename();
    String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."),oldName.length());
    file.transferTo(new File(folder,newName));//保存文件
    String url = req.getScheme() + "//" + req.getServerName() + ":" + req.getServerPort() + "/img" + format + newName;
    System.out.println(url);//文件的访问路径
  }

}

至此,我们的文件上传功能已实现,我们还可以继续在application.properties中增加一些文件属性相关信息

#上传的单个文件的大小
spring.servlet.multipart.max-file-size=1MB
#上传的文件总大小
spring.servlet.multipart.max-request-size=10MB
#文件上传临时保存目录
spring.servlet.multipart.location=
#文件上传临界值(超过这个临界值,就要保存到location中去了)
spring.servlet.multipart.file-size-threshold=1MB

 

你可能感兴趣的:(SpringBoot)