file.transferTo的踩坑实纪(Vue,SpringBoot)

今天前后端联调的时候报了个奇怪的错误:

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();

}

这样就可以把一个前端传入的流(这个应用场景是图片),存进三个不同的路径里了!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值