wycayj的gravatar头像
wycayj 2017-05-16 22:42:14

为什么java使用MultipartFile的transferTo()方法不能使用两次?

我想将一个文件同时上传到两个路径下保存,使用了MultipartFile的transferTo()方法两次,第二次就报错了,应该怎么去解决

所有回答列表(2)
最代码官方的gravatar头像
最代码官方  LV167 2017年5月16日

因为http post文件流只可以接收读取一次,传输完毕则关闭流。

可以把流保存为文件1,然后对文件1进行复制,移动等操作。

mjxin123456的gravatar头像
mjxin123456  LV10 2021年11月25日
因为java中读取流,他的内部光标不会重置在起始位置,至于光标重置的方法,尝试了几次也不行,只能用流的复制

public void importFile(MultipartFile file){

//复制原始流
InputStream inputStream = file.getInputStream();
ByteArrayOutputStream baos = FileUtil.cloneInputStream(inputStream);


for (int i = 0; i < size; i++) {
   //循环多少次,从原始流中就取多少次,
    InputStream contentStream = new ByteArrayInputStream(baos.toByteArray());
    
    ........相关代码

    contentStream.close();//关闭流

}



/**
复制流的方法
*/

    public static ByteArrayOutputStream cloneInputStream(InputStream input) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = input.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            return baos;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

 

顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友