transferto遇到的问题java.io.FileNotFoundException: C:\Users\Administrator\AppData\Local\Temp
问题描述(image.transferTo(file))
今天小编我在一个Spring Cloud项目中写文件或图片上传的过程中遇到了一个问题,就是在使用image.transferTo(file)时报错,错误信息如下:
java.io.FileNotFoundException: C:\Users\Administrator\AppData\Local\Temp\E:\image\info (文件名、目录名或卷标语法不正确。)
可以看到,这里显示的其实是有两个路径,后面的路径E:\image\info是我要上传文件的目标路径,而前面的路径应该是调用image.transferTo(file)生成的一个默认路径,我百度了很多解决方案都没解决。
解决方法
解决前的代码:重点关注代码片段image.transferTo(file)
public void saveOrUpdateImageFile(Info bean, MultipartFile image, HttpServletRequest req)
throws Exception {
String filepath="E:/image/info";//指定图片上传到哪个文件夹的路径
File imageFolder = new File(filepath);
System.out.println(imageFolder);
File file = new File(imageFolder, bean.getId() + ".jpg");
System.out.println(file);
if (!file.getParentFile().exists())
file.getParentFile().mkdirs();
image.transferTo(file);//出错地方
//以下片段用来判断文件是否jpg格式,不需要看
BufferedImage img = ImageUtil.change2jpg(file);
System.out.println(img);
ImageIO.write(img, "jpg", file);
}
解决后的代码:将image.transferTo(file)改为FileUtils.copyInputStreamToFile(image.getInputStream(), file);
解决方案:引入commons-io的Maven依赖包
然后import org.apache.commons.io.FileUtils;
public void saveOrUpdateImageFile(Info bean, MultipartFile image, HttpServletRequest req)
throws Exception {
String filepath="E:/image/info";//指定图片上传到哪个文件夹的路径
File imageFolder = new File(filepath);
System.out.println(imageFolder);
File file = new File(imageFolder, bean.getId() + ".jpg");
System.out.println(file);
if (!file.getParentFile().exists())
file.getParentFile().mkdirs();
FileUtils.copyInputStreamToFile(image.getInputStream(), file);
//以下片段用来判断文件是否jpg格式,不需要看
BufferedImage img = ImageUtil.change2jpg(file);
System.out.println(img);
ImageIO.write(img, "jpg", file);
}
问题就这样子解决了。。。。。。。。