2

I have a JAX RS method that accepts the uploaded file as follows

@POST
@Path("/entity/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(@FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail)   {
  // Upload this file to another remote API again on secret server
}

Can someone suggest how can I use InputStream to forward this file to another server that has similar consumer ?

I tried this, which did not work. Something is missing

// Using com.ning.http.client.AsyncHttpClient
final FluentCaseInsensitiveStringsMap map = new   FluentCaseInsensitiveStringsMap();
map.add("file", fileDetail.getFileName());
map.add("Content-Type","multipart/form-data; boundary=" + boundary);
AsyncHttpClient.BoundRequestBuilder requestBuilder = asyncHttpClient.preparePost(postURL);
Response response = requestBuilder.setBody(IOUtils.toByteArray(uploadedInputStream)).setHeaders(map).execute().get();
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
DanglingPointer
  • 261
  • 1
  • 6
  • 19

2 Answers2

4

I'm guessing you're using Jersey. In that case just use the Jersey client API. You already have the multipart support dependency. You just need to use the correct APIs. For example

FormDataMultiPart multiPart = new FormDataMultiPart()
        .field("file", uploadedInputStream, MediaType.MULTIPART_FORM_DATA);
Client client = ClientBuilder.newClient();
String url = "...";
Response response = client.target(url).request()
        .post(Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE));
String responseAsString = response.readEntity(String.class);

See more information

Not sure what Jersey version you are using, but the above is the Jersey 2.x client API. If you are using Jersey 1.x, the API is a little different. See here for example

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • 1
    Thanks - you made my day. It worked. Small edit required : .post(Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE)); – DanglingPointer Apr 18 '15 at 07:46
  • I am trying to do the exact same thing using Jersey 2, but my receiving endpoint always returns 400, even though it has the exact same resource method signature. Any ideas or recommendations ? – Marco Lamina Jul 18 '16 at 07:56
  • I found the problem. Jersey only adds a correct multipart boundary if you create the entity like this: Entity.entity(multipart, MultiPartMediaTypes.createFormData()). Found the answer here: http://stackoverflow.com/questions/19134739/jersey-apacheconnector-multipart-file-upload-no-multipart-boundary-was-found – Marco Lamina Jul 18 '16 at 09:49
  • I'm trying this, but i'm setting .field is (String String) for FormDataMultiPart ... hmm – Mercyful Jun 13 '17 at 20:30
0

Try this

import com.ning.http.client.*;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
    @Test
        public void post() throws IOException, InterruptedException {
            File tmpFile = File.createTempFile("textbytearray", ".txt");
            AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
            AsyncHttpClient.BoundRequestBuilder builder = asyncHttpClient.preparePost("http://xxxxxxxxx");
            String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL";
            builder.addHeader("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            builder.setBodyEncoding("UTF-8");
            FilePart part = new FilePart("audio", tmpFile, "", "");
            builder.addBodyPart(part);
            builder.addBodyPart(new StringPart("from", "1"))
                    .execute(new AsyncCompletionHandler<Response>() {

                        @Override
                        public Response onCompleted(Response response) throws Exception {
                            System.out.println(response.getResponseBody());
                            return response;
                        }

                        @Override
                        public void onThrowable(Throwable t) {
                            System.out.println(t);
                        }
                    });

            Thread.sleep(1000000);
        }
MadeInChina
  • 130
  • 6