spring mvc MultipartFile 上传文件错误解决

Field error in object 'xxxx' on field 'xxxx': rejected value [20129259128131.jpg]; codes [typeMismatch.xxxx.xxxx,typeMismatch.xxxx,typeMismatch.org.springframework.web.multipart.MultipartFile,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [xxxx.xxxx,xxxx]; arguments []; default message [shoplogo_]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'org.springframework.web.multipart.MultipartFile' for property 'shoplogo_'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.springframework.web.multipart.MultipartFile] for property 'shoplogo_': no matching editors or conversion strategy found]



出现类似错误,检查form表单属性是否写上enctype="multipart/form-data"。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
你可以使用Java的javax.imageio包来实现MultipartFile图片的压缩。下面是一个使用Spring MVCMultipartFile进行图片压缩的示例代码: ```java import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class ImageCompressor { public static void compressImage(MultipartFile file, String outputFilePath, int maxWidth, int maxHeight) throws IOException { BufferedImage image = ImageIO.read(file.getInputStream()); int originalWidth = image.getWidth(); int originalHeight = image.getHeight(); // 计算缩放比例 double scaleFactor = Math.min((double) maxWidth / originalWidth, (double) maxHeight / originalHeight); int newWidth = (int) (originalWidth * scaleFactor); int newHeight = (int) (originalHeight * scaleFactor); // 创建缩放后的图像 BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = resizedImage.createGraphics(); g2d.drawImage(image, 0, 0, newWidth, newHeight, null); g2d.dispose(); // 将缩放后的图像保存到文件 ImageIO.write(resizedImage, "jpg", new File(outputFilePath)); } } ``` 使用时,你可以在Spring MVC的controller中调用`compressImage`方法来实现图片压缩。需要传入要压缩的MultipartFile对象、输出文件路径、以及期望的最大宽度和最大高度。 注意:上述示例代码仅适用于压缩JPEG格式的图片,如果需要处理其他格式的图片,可以根据需要进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值