I am trying to pass few parameters, which includes byte[] as one, to a Rest Service. In the Service method when I consume the parameter and construct a File out of it ...I see a corrupted file. Below is my code:
public class MultiParameters {
@JsonProperty(value="strName")
public String strName;
@JsonProperty(value="in")
public byte[] in;
public String strName2;
public String getStrName2() {
return strName2;
}
public void setStrName2(String strName2) {
this.strName2 = strName2;
}
public String getStrName() {
return strName;
}
public void setStrName(String strName) {
this.strName = strName;
}
public byte[] getIn() {
return in;
}
public void setIn(byte[] in) {
this.in = in;
}
RestController:
@RequestMapping(value= "/upload", method = RequestMethod.POST)
public void upload(@RequestBody MultiParameters obj){
try {
System.out.println("str name : "+obj.getStrName());
System.out.println("str name2 : "+obj.getStrName2());
System.out.println("bytes lenghts : "+obj.getIn());
FileOutputStream fos = new FileOutputStream(new File("D:\\Test.txt"));
fos.write(obj.getIn());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Can any one let me know what is the error over here?
I am testing my service by passing input as RAW Data in the form of JSON using Post Man.
Thanks.
We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument.
In Java, strings are objects that are backed internally by a char array. So to convert a string to a byte array, we need a getBytes(Charset) method. This method converts the given string to a sequence of bytes using the given charset and returns an array of bytes. It is a predefined function of string class.
The simplest way to do so is using parseByte() method of Byte class in java. lang package. This method takes the string to be parsed and returns the byte type from it.
You can encode your byte array into Base64 string, then decode it back to byte array after receiving in controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With