spring-boot文件上传的坑

在单纯使用spring-mvc的时候,配置文件上传,配置一个视图解析器便可,以下:java

<bean id="multipartResolver"
	class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<property name="maxUploadSize">
		<value>5120000</value>
	</property>
	<property name="maxInMemorySize">
		<value>1024</value>
	</property>
</bean>

最近在研究spring-boot,写一个demo,在java代码里面配置如上的Bean,无论怎么提交表单,controller就是接收不到文件,表单中的其余文本字段参数却能够正常接收到。web

在spring-boot的官方文档看到了multipart的配置,把如上的Bean配置代码去掉,在application.properties加上配置以下spring

# spring-boot自带的文件上传配置。
# 容许上传
spring.http.multipart.enabled=true
# Threshold after which files will be written to disk. Values can use the suffixed "MB" or "KB" to indicate a Megabyte or Kilobyte size.
spring.http.multipart.file-size-threshold=0
# 上传文件的临时目录
# spring.http.multipart.location=
# 单个文件的大小限制
spring.http.multipart.max-file-size=1MB
# 整个请求的大小限制
spring.http.multipart.max-request-size=10MB
# 不懒加载 
spring.http.multipart.resolve-lazily=false

controller接收文件的代码以下spring-mvc

/**
 * 文件上传
 * 
 * @param file
 * @return
 * @author wei.ss
 */
@RequestMapping(value = "/fileUpload", method = RequestMethod.POST, produces = { MediaType.TEXT_PLAIN_VALUE })
@ResponseBody
public String fileUpload(@RequestParam("file1") MultipartFile file,
		String name) throws Exception {

	LOG.info("fileUpload file={}, name={}", file, name);
	if (null == file) {
		return "file not found";
	}

	name = file.getOriginalFilename();
	LOG.info("{}={}", name, file);

	if (file.getSize() == 0) {
		LOG.warn("文件没有内容:{}", name);
	}

	LOG.info("{} file's length is {}", name, file.getBytes().length);

	return "ok";
}
相关文章
相关标签/搜索