@PostMapping("/upload")
public void uploadFile(MultipartFile file){
InputStream streamOne;
InputStream streamTwo;
InputStream inputStream;
try {
inputStream = file.getInputStream();
} catch (IOException e) {
log.error("Get file stream exception", e);
throw new IllegalArgumentException("文件上传失败");
}
ByteArrayOutputStream baos = copyInputStream(inputStream);
streamOne = new ByteArrayInputStream(baos.toByteArray());
streamTwo = new ByteArrayInputStream(baos.toByteArray());
//业务处理
//....
}
/**
* 流复制
*/
private static ByteArrayOutputStream copyInputStream(InputStream input) {
try {
//spring 计时器
Stopwatch stopWatch = Stopwatch.createStarted();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 定义一个缓存数组,临时存放读取的数组
byte[] buffer = new byte[4096];
int length;
while ((length = input.read(buffer)) > -1) {
baos.write(buffer, 0, length);
}
baos.flush();
stopWatch.stop();
log.info("流拷贝,总耗时[{}] ms", stopWatch.elapsed(TimeUnit.MILLISECONDS));
return baos;
} catch (IOException e) {
log.error("Stream copy exception", e);
}
throw new IllegalArgumentException("文件上传失败");
}
}
文件流复制
最新推荐文章于 2023-04-13 23:42:49 发布