美文网首页Spring Boot
Webflux上传文件处理

Webflux上传文件处理

作者: EasyNetCN | 来源:发表于2021-06-29 15:38 被阅读0次
    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";
                }
            });
        }
    }
    

    相关文章

      网友评论

        本文标题:Webflux上传文件处理

        本文链接:https://www.haomeiwen.com/subject/wwckultx.html