0

Can I have a rest service that can be used for file upload i.e. multi-part form data and JSON parameter? Below is the example of the service.

    @POST
    @Path("/upload")
    @Consumes({ MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_JSON })
    public Response uploadFile(@FormDataParam("file") InputStream uploadedInputStream,@FormDataParam("file") FormDataContentDisposition fileDetail, City city){

The problem is while testing I am trying to pass both file as an attachment and city object as JSON, it is giving me error as Content-Type could either be application/json or multipart/form-data.

Let me know if there is any way to handle this

Anand
  • 20,708
  • 48
  • 131
  • 198

3 Answers3

1

You may Use Any Client Side Language to submit form with MultipartFile and Json data. I am writing Java Code in Spring MVC here. It will send String Json and MultiPartFile. then Me going to to Cast String JSON to Map, and Save File at Desired Location.

@RequestMapping(value="/hotel-save-update", method=RequestMethod.POST )
public @ResponseBody Map<String,Object> postFile(@RequestParam(value="file", required = false) MultipartFile file,
                                     @RequestParam(value = "data") String object ){

    Map<String,Object> map = new HashMap<String, Object>();
    try {
        ObjectMapper mapper = new ObjectMapper();
        map = mapper.readValue(object, new TypeReference<Map<String, String>>(){});
    }catch (Exception ex){
        ex.printStackTrace();
    }

    String fileName = null;

    if (file != null && !file.isEmpty()) {
        try {

            fileName = file.getOriginalFilename();
            FileCopyUtils.copy(file.getBytes(), new FileOutputStream(servletContext.getRealPath("/resources/assets/images/hotelImages") + "/" + fileName));

        } catch (Exception e) {
            header.put(Utils.MESSAGE, "Image not uploaded! Exception occured!");
            return result;
        }
    }

}

Muhammad Sadiq
  • 434
  • 4
  • 10
0

Can't you leave the @Consumes off and check the Content-Type header in the method itself, deciding what to do in code? Your problem seems to be a restriction in the functionality of that annotation (is it Spring MVC?)

Richard
  • 1,070
  • 9
  • 22
  • That is when the client needs to send either of one..but what if client wants to send both..file and json...is it possible? – Anand Feb 05 '15 at 12:06
  • So you say you have a client that is doing both things in the same request? How does the client do that? – Richard Feb 05 '15 at 12:32
0

I have solved my problem by passing JSON as String from client and then converting String to JSON object.

    @POST
    @Path("/upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(@FormDataParam("file") InputStream uploadedInputStream,
                                @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("city") String city){
Anand
  • 20,708
  • 48
  • 131
  • 198