spring-boot文件上传的坑

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

<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就是接收不到文件,表单中的其他文本字段参数却可以正常接收到。

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

# 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接收文件的代码如下

/**
 * 文件上传
 * 
 * @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";
}

 

转载于:https://my.oschina.net/u/2007041/blog/904680

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值