SpingBoot2.x文件上传:failed to convert java.lang.String to org.springframework.util.unit.DataSize

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fly910905/article/details/90598418

问题现象:

SpringBoot项目由1.5.x升级到2.x,文件上传启动报错

配置文件

#文件上传路径 linux配置路径
spring.servlet.multipart.max-file-size=50Mb
spring.servlet.multipart.max-request-size=50Mb
file.upload.realpath=D:/csizgcardmanage/files

报错信息

Failed to bind properties under 'spring.servlet.multipart.max-request-size' to org.springframework.util.unit.DataSize:

    Property: spring.servlet.multipart.max-request-size
    Value: 50Mb
    Origin: class path resource [application-dev.properties]:36:43
    Reason: failed to convert java.lang.String to org.springframework.util.unit.DataSize

Action:

Update your application's configuration

原因分析:

转换为Long型的数值

	/**
	 * Obtain a {@link DataSize} representing the specified number of megabytes.
	 * @param megabytes the number of megabytes, positive or negative
	 * @return a {@link DataSize}
	 */
	public static DataSize ofMegabytes(long megabytes) {
		return new DataSize(Math.multiplyExact(megabytes, BYTES_PER_MB));
	}

通过源码分析,我们知道,文件上传的数值,需要是Long型

spring.servlet.multipart.max-file-size=50000000

单位的英文全大写(推荐)

带单位的字符串是支持的,不过单位的英文貌似必须写全而且是全大写,比如5MB、5KB、5B(5)这样,DataSize有个parse(CharSequence text)方法

	/**
	 * Obtain a {@link DataSize} from a text string such as {@code 12MB} using
	 * {@link DataUnit#BYTES} if no unit is specified.
	 * <p>
	 * Examples:
	 * <pre>
	 * "12KB" -- parses as "12 kilobytes"
	 * "5MB"  -- parses as "5 megabytes"
	 * "20"   -- parses as "20 bytes"
	 * </pre>
	 * @param text the text to parse
	 * @return the parsed {@link DataSize}
	 * @see #parse(CharSequence, DataUnit)
	 */
	public static DataSize parse(CharSequence text) {
		return parse(text, null);
	}

通过源码分析,带单位的字符串是支持的,不过单位的英文貌似必须写全而且是全大写,比如5MB、5KB

spring.servlet.multipart.max-file-size=50MB

猜你喜欢

转载自blog.csdn.net/fly910905/article/details/90598418