Play 2.0 How to Post MultipartFormData using WS.url or WS.WSRequest

后端 未结 6 1328
小蘑菇
小蘑菇 2021-02-08 22:42

In Java Http request, we can do this to make multipart HTTP POST.

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);

FileBo         


        
6条回答
  •  面向向阳花
    2021-02-08 23:45

    Working example for play 2.3 using above approach, also added contentType while uploading the file.

    public Promise upload(Http.MultipartFormData.FilePart policyFilePart, String contentType) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        List parts = new ArrayList<>();
        try {
            parts.add(new FilePart("file", policyFilePart.getFile(), contentType, null));
            parts.add(new StringPart("param1", "value1"));
            parts.add(new StringPart("param2", "value2"));
            Part[] partsA = parts.toArray(new Part[parts.size()]);
    
            // Add it to the multipart request entity
            MultipartRequestEntity requestEntity = new MultipartRequestEntity(partsA, new FluentCaseInsensitiveStringsMap());
            requestEntity.writeRequest(bos);
            InputStream reqIS = new ByteArrayInputStream(bos.toByteArray());
            return WS.url(baseUrl + "upload")
                    .setContentType(requestEntity.getContentType())
                    .post(reqIS).map(new Function() {
                        @Override
                        public WSResponse apply(WSResponse wsResponse) throws Throwable {
                                return wsResponse;
                        }
                    });
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    

提交回复
热议问题