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";
}
相關文章
相關標籤/搜索