今天前后端联调的时候报了个奇怪的错误:
java.io.FileNotFoundException: (系统找不到指定的路径。)
实际的应用场景是用富文本编辑器上传图片,很简单的一个过程,只是需求比较特殊,要求这个图片分别存在三个路径下。
原代码:
public ImgResult imgUpload(@RequestParam("file")MultipartFile file)throws IOException{
filePathName='[第一个路径]';
filePathName2='[第二个路径]';
filePathName3='[第三个路径]';
//存入第一个路径
File saveFile new File(filePathName);
saveFile.createNewFile();
file.transferTo(saveFile);
//存入第二个路径
File saveFile2 new File(filePathName2);
saveFile2.createNewFile();
file.transferTo(saveFile2);
//存入第三个路径
File saveFile3 new File(filePathName3);
saveFile3.createNewFile();
file.transferTo(saveFile3);
}
讲道理它应该存进三个路径里,然而报错。
然后诡异的是,当我把路径缩减到1个的时候,成功了?!
问题就出在file.transferTo上,这玩意只能用一次(输入流只能用一次),其实这也合理,但总是有特殊情况的需求,那该怎么使用三次file呢
public ImgResult imgUpload(@RequestParam("file")MultipartFile file)throws IOException{
filePathName='[第一个路径]';
filePathName2='[第二个路径]';
filePathName3='[第三个路径]';
// 把前端输入进来的流用byte形式存下来
byte[] bytes = file.getBytes();
//存入第一个路径
// 定义一个输出流,为保存的路径
Fileoutputstream fileoutputstream new Fileoutputstream(filePathName);
// 把byte流拿出当输入流(现在就可以多次使用啦)
ByteArrayInputstream byteArrayInputstream new ByteArrayInputstream(bytes);
// 这个应该是java自带的工具类,把输入流的内容拷给输出流
IoUtil.copy(byteArrayInputstream,fileoutputstream);
//流用完要记得关!!
fileoutputstream.close();
byteArrayInputstream.close();
//存入第二个路径
Fileoutputstream fileoutputstream2 new Fileoutputstream(filePathName2);
ByteArrayInputstream byteArrayInputstream2 new ByteArrayInputstream(bytes);
IoUtil.copy(byteArrayInputstream2,fileoutputstream2);
fileoutputstream2.close();
byteArrayInputstream2.close();
//存入第三个路径
Fileoutputstream fileoutputstream3 new Fileoutputstream(filePathName3);
ByteArrayInputstream byteArrayInputstream3 new ByteArrayInputstream(bytes);
IoUtil.copy(byteArrayInputstream3,fileoutputstream3);
fileoutputstream3.close();
byteArrayInputstream3.close();
}
这样就可以把一个前端传入的流(这个应用场景是图片),存进三个不同的路径里了!