本文主要讲述webflux文件上传 在工作中我们经常遇到需要上传文件至服务器,SpringMVC文件上传网上已有很多案例,但照搬到Webflux则行不通。原因在于在webflux中没有MultipartFile接口的实例,webflux是用FilePart这个接口传递文件的。 我的应用场景是将图片上传至阿里云的OSS,OSSSDK提供了一个将InputStream上传的接口。而要拿到InputStream我需要拿到File因此我借鉴网上的方案写了一个单文件上传的接口,同时发现网上并没有多文件上传的实例,于是有多加改进支持多文件上传。
1.单文件上传
public Mono single(@RequestPart ("file") Mono file) throws IOException {
return file.map(filePart->{
Path tempFile = null;
try {
tempFile = Files.createTempFile("test", filePart.filename());
} catch (IOException e) {
e.printStackTrace();
}
AsynchronousFileChannel channel = null;
try {
channel = AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE);
} catch (IOException e) {
e.printStackTrace();
}
DataBufferUtils.write(filePart.content(), channel, 0).doOnComplete(() -> {
System.out.println("finish");
}).subscribe();
return tempFile;
}).map(a->{
return a.toFile();
//此时已转换为File类,具体的业务逻辑我就忽略了
}).flatMap(fileSinge->file.map(FilePart::filename));
}
2.多文件上传
public Mono more(@RequestPart ("file") Flux file) throws IOException {
return file.map(filePart->{
Path tempFile = null;
try {
tempFile = Files.createTempFile("test", filePart.filename());
} catch (IOException e) {
e.printStackTrace();
}
filePart.transferTo(tempFile.toFile());
return tempFile;
}).map(a->{
return a.toFile();
//此时已转换为File类,具体的业务逻辑我就忽略了
}).flatMap(fileSinge->file.map(FilePart::filename)).collectList();
}
|