I will have to do some development and I will need your logic please, I'll try to be as clear as possible
I have a JSON file that will be sent to a Web Service to process it.
When the file arrives on this Web Service, I have to parse it.
First question : Is it a @PostMapping to recover this file?
Since it's a file, I get it as a file like this:
@PostMapping( value="/getFile",
consumes = {"multipart/form-data"})
public void postFile(@RequestParam() MultipartFile file) throws IOException
I recover the file well, but the concern is that the @RequestParam parameter expects a file name, except that when the file is sent to the web service, I do not know its name yet,
Second Question :
So how do you parse this file into a string?
Thank you in advance for your precious help
CodePudding user response:
For the first question:
Yep, @PostMapping is the right way to go. Regarding the file name bit, @RequestParam() does not expect the file name to be passed, it expects the "key" of the key-value pair where the value is the file being uploaded. For example, when sending a file via a RestTemplate call, the file would be included in the POST call as somewhat like this:
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("uploadFile", getFileToUpload());
Here the key is "uploadFile", so your controller will look like this :
@PostMapping( value="/getFile",
consumes = {"multipart/form-data"})
public void postFile(@RequestParam("uploadFile") MultipartFile file) throws IOException
Checkout this tutorial : https://spring.io/guides/gs/uploading-files/
For the second question:
ByteArrayInputStream stream = new ByteArrayInputStream(file.getBytes());
String myFileString = IOUtils.toString(stream, StandardCharsets.UTF_8);
This should do. Cheers