- Controller配置
以具体代码为通过时间为文件夹分类上传的文件
/** * * @Title: upload * @Description: 上传图片 * @param file * @throws IOException * @return String * @throws */ @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public ResultBean<String> upload(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException { byte[] bytes = file.getBytes(); String originalFilename = file.getOriginalFilename(); int indexOf = originalFilename.indexOf("."); String extend = originalFilename.substring(indexOf); String format = DateUtils.format(new Date(), DateUtils.YYYYMMDD); String nowFileName = DateUtils.format(new Date(), DateUtils.YYYYMMDDHHMMSS); String strPath = "upload/" + format; File path = new File(strPath); if (!path.exists()) { path.mkdirs(); } // 这样默认上传文件就放在当前 项目路径下 StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(strPath).append("/").append(nowFileName).append(extend); File name = new File(stringBuilder.toString()); FileCopyUtils.copy(bytes, name); ResultBean<String> resultBean = new ResultBean<String>(); resultBean.setData(stringBuilder.toString()); return resultBean; }
(上图为最后上传的效果)
- application.properties
###########springboot文件上传 #spring.http.multipart.location=upload #最大文件上传 spring.http.multipart.max-file-size=1MB #最大请求 spring.http.multipart.max-request-size=100MB
- 上传出错捕获
以下主要是,针对异步请求上传出错的捕获,捕获之后通过Redis发布与订阅者模式,将错误日志异步发送给订阅者,然后存储到elasticsearch中(以下代码中没有涉及)
- 源码配置解析
location
specifies the directory where files will be stored. The default is "". A common value is to use the system's temporary directory, which can be obtained.
//location指定存储文件的目录。默认的是“”。一个常见的值是使用系统的临时目录,该目录可以获得。
//如果指定了locationname其实在默认tomcat记录路径上存储上传的文件,不易查找,建议上传专门指定文件上传目录
max-file-size
specifies the maximum size permitted for uploaded files. The default is 1MB.
//指定上传文件允许的最大大小。默认是1 mb。
max-request-size
specifies the maximum size allowed for multipart/form-data requests. The default is 10MB
//指定允许多部分/表单数据请求的最大大小。默认值是10 mb
file-size-threshold
specifies the size threshold after which files will be written to disk. Default is 0, which means that the file will be written to disk immediately.
//指定文件写入磁盘后的大小阈值。默认值是0,这意味着文件将立即写入磁盘。
微信公众号