Anand
Anand

Reputation: 21320

Rest service Java for file upload and JSON data

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

Upvotes: 0

Views: 13024

Answers (3)

Muhammad Sadiq
Muhammad Sadiq

Reputation: 434

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;
        }
    }

}

Upvotes: 1

Anand
Anand

Reputation: 21320

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){

Upvotes: 0

Richard
Richard

Reputation: 1130

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?)

Upvotes: 0

Related Questions