0

I'm implementing RESTful webservice by using Spring framework. There is a scenario where I need to accept the request where a field of request body will be a file(PDF or Image). My request body will look like :

{
  "id" : "101",
  "name" : "John",
  "report" : 
}

Here report field in above request body will be a file(PDF or Image). I read many articles on this but unable to get the proper answer. I got the solution for accepting the file alone but not file as a field of request body Please help me out

Saurabh
  • 867
  • 3
  • 13
  • 28

3 Answers3

3

Okay, there are many approaches for this. I will explain one such approach.

Step 1: Create StudentReport class.

Notice the byte[] array used here.

public class StudentReport {

    private long id;
    private String Name;
    byte[] report;

    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return Name;
    }
    public void setName(String name) {
        Name = name;
    }
    public byte[] getReport() {
        return report;
    }
    public void setReport(byte[] report) {
        this.report = report;
    }

}

Step 2 : Create the required rest end point.

Here I wish to tell you few things. The Json has to be send to end point as string and keep the report empty there. This will be passed seperatley like shown below.

@RestController
@RequestMapping("/NameYourController/")
public class MyController{


    @RequestMapping(value = "addDetails", method = RequestMethod.POST , consumes = "multipart/form-data")
    public StudentReport addProduct(@RequestParam String studentReportJson, @RequestParam MultipartFile report) throws JsonParseException, JsonMappingException, IOException {


        //Convert your Json in Strign format as actual object
        StudentReport studentReport  = new ObjectMapper().readValue(studentReportJson, StudentReport.class);

        //convert file to byte array
        byte[] myReport = report.getBytes();

        studentReport.setReport(myReport); 

        // Now, pdf is set in the object
        // do whatever you want to do with it like save in database etc
        //based on that , have some return type defined. I have just used returned the object in this example .
        return studentReport; // Spring boot auto converts this object to Json when send to UI.Note that Json is an object and Json String is string object consisting of Json. We recieved Json String but returning Json object


    }

    //and other endpoints you want to define
}

That's it done. Note that for this you need to import the Jackson library. If you are using Maven, you can add this in your pom.xml.

<dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.12</version>
</dependency>

Now, how would you test your rest end point. One way will be from the UI code which will consume these.But then be sure of that code that it is correct. If you don't have UI code still you can do this. This is done by chrome app PostMan. But, for that you need to use chrome web browser.

Youtube have lots of videos on how to use PostMan. I will just give you a screen shot of how to use specifically in your case :

Notice these things in image -> POST, URL Path, BODY , form-data, TEXT , FILE. :)
Output will be displayed below in postman if you have some return data.(not shown in image)

enter image description here

Number945
  • 4,631
  • 8
  • 45
  • 83
0

JSON Doesn't support Binary Data. You must encode your File as a Base64 String and attach it.

{
  "id" : "101",
  "name" : "John",
  "report" : "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCABkAGQDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDxyiiiv3E8wKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//Z"
}

This above Base64 Encoding is for a Image file from here

Community
  • 1
  • 1
shazin
  • 21,379
  • 3
  • 54
  • 71
0

You must use a @RequestParam or @RequestPart to send and process a file. It is not impossible to use @ResponseBody, but for that you have to write your custom converters.

public String handleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {

 // Your File Processing goes here

}

Why cant we get a file data from a RequestBody in java?

Community
  • 1
  • 1
zeagord
  • 2,257
  • 3
  • 17
  • 24