1、文件上传:
Controller:
@PostMapping("/import")public void importImage(@RequestPart("file") FilePart filePart) {imageService.importImage(filePart);}
Service:
public void importImage(FilePart filePart) {File saveFile = new File("/tmp/a.txt");if (!copyFile(filePart, saveFile)) {throw new OpsManagerException("文件保存失败!");}}
public boolean copyFile(FilePart filePart, File tempFile) {try {if (tempFile.exists()) {tempFile.delete();}tempFile.createNewFile();AsynchronousFileChannel channel = AsynchronousFileChannel.open(tempFile.toPath(), StandardOpenOption.WRITE);AtomicBoolean copyFinish = new AtomicBoolean(false);DataBufferUtils.write(filePart.content(), channel, 0).doOnComplete(() -> copyFinish.set(true)).subscribe();AtomicInteger atomicInteger = new AtomicInteger(0);while (!copyFinish.get()) {Thread.sleep(5000);atomicInteger.addAndGet(1);if (atomicInteger.get() > 720) {throw new OpsManagerException("文件过大");}}return true;} catch (Exception e) {log.error("save upload file error", e);return false;}}
2、文件下载:
Controller:
@GetMapping("/export")public Mono<Void> downloadFile(ServerHttpResponse response) {File file = new File("/tmp/workplace.zip");return TaskUtils.downloadFile(file, response);}
Service:
public static Mono<Void> downloadFile(File file, ServerHttpResponse response) {try {response.getHeaders().set(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));response.getHeaders().setContentType(MediaType.APPLICATION_OCTET_STREAM);response.getHeaders().set(HttpHeaders.CONTENT_LENGTH, "" + file.length());Flux<DataBuffer> dataBufferFlux = Flux.create((FluxSink<DataBuffer> emitter) -> {InputStream in = null;try {in = new FileInputStream(file);byte[] buffer = new byte[1024 * 1024]; // Adjust buffer size based on your needswhile (in.read(buffer) != -1) {emitter.next(response.bufferFactory().wrap(buffer));}emitter.complete();} catch (IOException e) {emitter.error(e);} finally {if (in != null) {try {in.close();} catch (IOException e) {e.printStackTrace();}}}});return response.writeAndFlushWith(Mono.just(dataBufferFlux));} catch (IOException ex) {logger.error("download file error!", ex);throw new RuntimeException("download file error!");}}