1

I am trying to POST multipart file as a form data to a REST service which returns me a url after it saved at REST service end. In postman the request look like this. enter image description here

I have a Spring Boot service which has a method to get Multipart file form frontend via jquery fileuploader. I need to post the file to the above URL which postman sends and saves in there end. I think i have to construct form data in my Spring boot service. Below are few snaps of the Spring boot service.

Controller end.

@RequestMapping(method = RequestMethod.POST, value = "/file-upload/{profileName:.+}")
  public Attachment uploadFile(@RequestParam("file") MultipartFile input,
   @PathVariable("profileName") String profileName) throws IOException {
   Attachment attachment = new Attachment();
   if (input != null) {
    log.info("Upload a new attachment item" + input.getName());
    byte[] fileByteArray = input.getBytes();
    attachment.setEncodedFile(Utils.encodeBytes(fileByteArray));
    attachment.setFileName(input.getOriginalFilename());

    socialMediaService.uploadMedia(input, profileName);

   }
   return attachment;
  }

SocialMediaService

  public String uploadMedia(MultipartFile input, String profileName) {

   String mediaUploadPath = "wall_attach/lenne-public";
   Map < String, String > params = new HashMap < > ();
   String mediaUploadFullPath =
    UrlBuilder.build(System.getenv(Constants.HUBZILLA_URL), mediaUploadPath, params);
   if (!isRestServiceProvided) {
    restService = new RestService(RequestType.POST, mediaUploadFullPath);
   }

   MultipartEntityBuilder builder = restService.getEntityBuilder();
   builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
   try {
    builder.addBinaryBody("userfile", input.getBytes(), ContentType.DEFAULT_BINARY, input.getOriginalFilename());
   } catch (IOException e) {
    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
   }

   String strResp = restService.execute(profileName, Constants.HUBZILLA_PW);
   return strResp;

  }

  return null;


  }

RestService class

public class RestService {

  private Logger log;

  private HttpClient client = null;
  private HttpRequest request = null;
  private RequestType reqType = null;
  private String body;
  MultipartEntityBuilder builder = null;

  public RestService() {
    this.log = LoggerFactory.getLogger(RestService.class);
  }

  /**
   * Create REST service with external parameters.
   *
   * @param reqType RequestType
   * @param client HttpClient
   * @param request External HttpRequest
   */
  public RestService(RequestType reqType, HttpClient client, HttpRequest request, Logger log) {
    this.reqType = reqType;
    this.client = client;
    this.request = request;
    this.log = log;
  }

  /**
   * Create REST service string parameters.
   * 
   * @param reqType RequestType
   * @param fullPath Full path of REST service
   */
  public RestService(RequestType reqType, String fullPath) {
    this.client = HttpClientBuilder.create().build();
    this.reqType = reqType;
    this.log = LoggerFactory.getLogger(RestService.class);


    if (reqType == RequestType.GET) {
      this.request = new HttpGet(fullPath);
    } else if (reqType == RequestType.POST) {
      this.request = new HttpPost(fullPath);
    } else if (reqType == RequestType.DELETE) {
      this.request = new HttpDelete(fullPath);
    }
  }

  /**
   * Execute REST service without authentication.
   * 
   * @return - Result of the service.
   */
  public String execute() {
    return execute(null, null);
  }

  /**
   * Execute REST web service with basic authentication.
   *
   * @return - Result of the service.
   */
  public String execute(String user, String password) {
    try {

      if (user != null && password != null) {
        StringBuilder authString = new StringBuilder();
        authString.append(user).append(":").append(password);
        String authBase = new String(
            Base64.getEncoder().encode(authString.toString().getBytes(Charset.forName("UTF-8"))));

        String authType = "Basic ";
        String authHeader = authType + authBase;

        request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
      }

      HttpResponse response = null;

      if (this.reqType == RequestType.GET) {
        HttpGet get = (HttpGet) request;
        response = client.execute(get);

      } else if (this.reqType == RequestType.POST) {
        HttpPost post = (HttpPost) request;

        if (body != null) {
          StringEntity stringEntity = new StringEntity(body);
          post.setEntity(stringEntity);
        }

        if (builder != null) {
          HttpEntity entity = builder.build();
          post.setEntity(entity);
        }
        response = client.execute(post);

      } else {
        throw new NotImplementedException();
      }

      if (response != null && (response.getStatusLine().getStatusCode() == Status.OK.getStatusCode()
          || response.getStatusLine().getStatusCode() == Status.CREATED.getStatusCode())) {
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity);
      }

    } catch (Exception e) {
      log.error("External service call failed ", e);
    }

    return null;
  }

  public void setBody(String body) {
    this.body = body;
  }

  public MultipartEntityBuilder getEntityBuilder() {
    this.builder = MultipartEntityBuilder.create();
    return this.builder;
  }


}

My problem is not getting any result after I executed the rest service upload media method. But it worked perfectly via postman.

Can anybody let me know what am I missing? Is the way I constructed the form data in java correct?

Thank you in advance.

Thusira Dissanayake
  • 153
  • 1
  • 4
  • 15

1 Answers1

0

Try adding consumes parameter in @RequestMapping like this (consumes = "multipart/form-data")

@RequestMapping(method = RequestMethod.POST, consumes = "multipart/form-data" ,value = "/file-upload/{profileName:.+}")
public Attachment uploadFile(@RequestParam("file") MultipartFile input,
    @PathVariable("profileName") String profileName) throws IOException {
----
----  
}

There is another relevant issue here: Trying to upload MultipartFile with postman Please read the comments under answer in this link. Hope it helps!

Khwaja Sanjari
  • 455
  • 5
  • 17
  • What I am worrying is the uploadMedia method in SocialMediaService class. I already have the file as a byte array, i need to create another formdata and post it to the 2nd service. just like my postman did – Thusira Dissanayake Oct 17 '18 at 04:23
  • I suppose you need to convert byte array to multpartfile format, Spring controller might be doing it automagically (automatically magic). Please refer https://stackoverflow.com/questions/18381928/how-to-convert-byte-array-to-multipartfile – Khwaja Sanjari Oct 17 '18 at 14:22
  • And Postman uploads files in multipartfile format so we might not need to do the conversion. – Khwaja Sanjari Oct 17 '18 at 14:29