创建输入流InputStream是需要文件对象或者文件地址
所以我们需要把MultipartFile转为文件,存储到临时文件,然后转为输入流
最后记得删除文件
关键代码其实就try代码快 中间 三行
// MultipartFile转换为InputStream
public InputStream multipartToInputStream(MultipartFile multipartFile) throws IOException {
InputStream inputStream = null;
File file = null;
try {
// 创建临时文件
file = File.createTempFile("temp", null);
// 把multipartFile写入临时文件
multipartFile.transferTo(file);
// 使用文件创建 inputStream 流
inputStream = new FileInputStream(file);
} catch (Exception e) {
e.printStackTrace();
}finally {
// 最后记得删除文件
file.deleteOnExit();
// 关闭流
inputStream.close();
}
return inputStream;
}
这里要注意:MultipartFile 中的transferTo(file)
MultipartFile中的transferTo(file)方法只能使用一次;
并且使用transferTo方法之后不可以在使用getInputStream()方法;
否则再使用getInputStream()方法会报异常java.lang.IllegalStateException: File has been moved - cannot be read again;
使用transferTo(file)方法将上传文件写到服务器上指定的文件;
原因文件流只可以接收读取一次,传输完毕则关闭流;