Search code examples
javaokhttpattask

OkHttpClient - How to set "[object Object]" to local file


I generated this code snippet from Postman and wanted to use it in Talend, but I don't know how to set the filename so that it pulls from the local drive. Here is the code:

OkHttpClient client = new OkHttpClient();

File sourceFile = new File("/Users/secret/Desktop/temp/16-27513/Digital Storefront Receipt.png");

MediaType mediaType = MediaType.parse("multipart/form-data; boundary=---011000010111000001101001");
RequestBody body = RequestBody.create(mediaType, "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"uploadedFile\"; filename=\"[object Object]\"\r\nContent-Type: false\r\n\r\n\r\n-----011000010111000001101001--");
Request request = new Request.Builder()
  .url("https://secret.attask-ondemand.com/attask/api-internal/upload/?apiKey=secret")
  .post(body)
  .addHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001")
  .addHeader("cache-control", "no-cache")
  .build();

Response response = client.newCall(request).execute();
String json = response.body().string();
System.out.println(json.toString());

This is the local file I want to reference in [object Object]: "/Users/secret/Desktop/temp/16-27513/Digital Storefront Receipt.png"

Been chewing at this for hours with no luck. Any help is much appreciated.


Solution

  • Thanks for the help BrianPipa. With Workfront in particular, the form key has to be "uploadedFile" and the value needs to match the referenced file. Using MultipartBody, it is easier to build the request body as opposed to using string. Final code:

    File sourceFile = new File("/Users/secret/Desktop/temp/16-27513/Digital Storefront Receipt.png");
    
    final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    
    RequestBody body = new MultipartBody.Builder()
                       .setType(MultipartBody.FORM)                                     
                       .addFormDataPart("uploadedFile", "Digital Storefront Receipt.png", RequestBody.create(MEDIA_TYPE_PNG ,sourceFile))
                       .build();
    
    Request request = new Request.Builder()
      .url("https://secret.attask-ondemand.com/attask/api-internal/upload/?apiKey=secret")
      .post(body)
      .addHeader("content-type", "multipart/form-data; boundary=---011000010111000001101001")
      .addHeader("cache-control", "no-cache")
      .build();
    
    OkHttpClient client = new OkHttpClient();
    
    Response response = client.newCall(request).execute();
    String json = response.body().string();
    System.out.println(json.toString());