Webflux上传文件处理

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;

import org.apache.commons.codec.binary.Base64;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;

import reactor.core.publisher.Mono;

@RestController
@RequestMapping("files")
public class FileServiceController {
    @PostMapping("upload")
    public Mono<String> upload(@RequestPart("file") FilePart filePart) {
        return filePart.content().map(b -> b.asInputStream(true)).reduce(SequenceInputStream::new).map(ins -> {
            try {
                var outSteam = new ByteArrayOutputStream();
                var buffer = new byte[1024];
                var len = -1;
                while ((len = ins.read(buffer)) != -1) {
                    outSteam.write(buffer, 0, len);
                }
                outSteam.close();
                ins.close();

                return Base64.encodeBase64String(outSteam.toByteArray());
            } catch (IOException ex) {
                ex.printStackTrace();

                return "false";
            }
        });
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容