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.
您可以将字节数组编码为Base64字符串,然后在控制器中接收后将其解码回字节数组。
By given code, I am guessing that you are trying to upload a file. If that is the case you can simply upload file and accept them in controller as mentioned in below example where we are accepting one customer object and one file object
@RequestMapping(value = "/registration/uploadFile", method = RequestMethod.POST)
public Customer saveFile(@RequestPart("customer") @Valid Customer customer, @RequestPart("file") @Valid MultipartFile file) {
return customerService.saveFile(customer, file);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.