使用 RESTful API 的多部分文件上传将大于 256K 的文件拆分为 1k 大小的缓冲区

问题描述

我用 SpringBoot 编写的反应式 RESTful API 的文件上传端点显然在服务器端将大于 256K 的文件分解为 1K 大小的块。我认为上传文件在服务器端缓冲在一块并编写了这段错误代码

      public Mono<ServerResponse> saveImage(ServerRequest request) {
            final Mono<DataBuffer> dataBuffer = request.body(BodyExtractors.toParts())
                            .filter(part -> part.name().equals(FILE_FIELD_NAME))
                            .cast(FilePart.class)
                            .flatMap(FilePart::content).elementAt(0);
            return dataBuffer.flatMap(buffer -> {
                final byte[] bytes = new byte[buffer.readableByteCount()];
                DataBufferUtils.release(buffer.read(bytes));
                final Photo photo = new Photo(
                        UUID.randomUUID().toString(),"image/jpeg",//Todo: Get this from the image file itself
                        new Binary(BsonBinarySubType.BINARY,bytes),getMD5Hash(bytes),new Date());
                return ServerResponse.ok()
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(photoService.savePhoto(photo).map(Hash::new),Hash.class);
            });
      }

elementAt(0) 调用获取通量中的第一个元素。它适用于小于 256K 的文件。该错误是针对大于 256K 的文件而发现的,在这种情况下 elementAt(0) 返回了一个 1K 字节的数组。解决方案是将助焊剂收集到单个缓冲液中,如下所示:

        public Mono<ServerResponse> saveImage(ServerRequest request) {
            final Mono<DataBuffer> dataBuffer = DataBufferUtils.join(request.body(BodyExtractors.toParts())
                            .filter(part -> part.name().equals(FILE_FIELD_NAME))
                            .cast(FilePart.class)
                            .flatMap(FilePart::content));
            return dataBuffer.flatMap(buffer -> {
                final byte[] bytes = new byte[buffer.readableByteCount()];
                DataBufferUtils.release(buffer.read(bytes));
                final Photo photo = new Photo(
                        UUID.randomUUID().toString(),new Binary(BsonBinarySubType.BINARY,Hash.class);
            });
        }

为什么 SpringBoot 或其他任何将大于 256K 的文件拆分为 1K 大小的缓冲区?这个可以配置吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)