首页 > 解决方案 > 播放应用程序 | 如何将 FilePart 传递给其他请求

问题描述

在 java play 应用程序中,我公开了文件的 Put 请求,我想在 wsClient 的另一个请求中使用这个 FilePart:

public CompletionStage<String> upload() {
        Http.RequestBody body = request().body();
        Http.MultipartFormData formData = body.asMultipartFormData();
        Http.MultipartFormData.FilePart<File> file = formData.getFile("file");

        return wsClient.url("fake")
                .setContentType("multipart/form-data")
                .post(Source.single(b))
                .thenApplyAsync(wsResponse -> {
                        return wsResponse.getBody();
                })
                .exceptionally(throwable -> throwable.getMessage());
    }

我得到了回应:'java.lang.UnsupportedOperationException: Unsupported Part Class'

感谢您的帮助

标签: javaplayframework

解决方案


此 post 端点将需要以下类型的主体:

Source<? super Http.MultipartFormData.Part<Source<ByteString, ?>>, ?>

可以通过以下方式从表单部件列表构建:

List<Http.MultipartFormData.Part> partList = new ArrayList<>();
Source<ByteString, ?> file = FileIO.fromFile(filePart.getFile());
Http.MultipartFormData.FilePart<Source<ByteString, ?>> filePart = new Http.MultipartFormData.FilePart<>(file.getKey(), file.getFilename(), filePart.getContentType(), file);
partList.add(filePart);

然后,您可以使用以下内容将其作为正文提供给帖子:

.post(Source.from(Collections.unmodifiableList(partList)))

推荐阅读