CommonsMultipartFile转File

项目上为了方便测试会将CommonsMultipartFile转File,我们可以利用CommonsMultipartFile类中的getInputStream()方法获得文件流然后转换成File

	public InputStream getInputStream() throws IOException {
		if (!isAvailable()) {
			throw new IllegalStateException("File has been moved - cannot be read again");
		}
		InputStream inputStream = this.fileItem.getInputStream();
		return (inputStream != null ? inputStream : StreamUtils.emptyInput());
	}

具体实现如下
先获取CommonsMultipartFile类型的文件

commonsMultipartFile = (CommonsMultipartFile) multipartHttpServletRequest.getFile("file");
File backFile = new File("随机文件的路径");
try {
		backFile.createNewFile();
	} catch (IOException e) {
		e.printStackTrace();
	}		
try {
		//调用InputStream转File的inputSteamToFile方法
		inputSteamToFile(commonsMultipartFile.getInputStream(),backFile);
	} catch (IOException e) {
		e.printStackTrace();
	}

InputStream转File的inputSteamToFile方法

 
    private static void inputSteamToFile(InputStream ins, File file){
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            while ((bytesRead = ins.read(buffer)) != -1){
                os.write(buffer,0,bytesRead);
            }
        }catch (Exception e){
                e.printStackTrace();
        }finally {
            try {
                if (os != null){
                    os.close();
                }
                if (ins != null){
                    os.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

完成后已将CommonsMultipartFile类型的文件转为File类型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值