I'm new to Spring and I have some troubles in receiving a .xls file from the front-end through a POST request. Bassicaly when I accesss the link "Project/File" I receive error code 400(bad request) but the parameters names are the same both in front-end and back-end.
Here is my code so far:
@Controller
public class RestController {
@Autowired
private FileService fileService;
@Consumes("application/vnd.ms-excel")
@RequestMapping(value = "Project/File",
method = {RequestMethod.POST, RequestMethod.GET},
params = {"inputXLS"})
public @ResponseBody void getCitiriContoriMecanici(
@RequestParam(value = "inputXLS" , required = true) InputStream inputStream) throws IOException{
//transform the InputStream to an array of bytes;
byte[] bytes = IOUtils.toByteArray(inputStream);
//create a new .xls file
File file = new File("TEST.xls");
FileOutputStream fileOutputStream = new FileOutputStream(file);
//write a the bytes to a new .xls file
fileOutputStream.write(bytes);
fileOutputStream.flush();
fileOutputStream.close();
fileService.getFileFromFrontEnd();//this method is used to parse the .xls file
}
}
Can anyone give me an idea how to solve this problem?
It looks like you're trying to implement a file upload control with a Jax-RS @Consumes
annotation. The first problem I see is that you're trying to directly consume application/vnd.ms-excel
, but that's not what your file upload will present coming from your front end. It expects multipart/form-data
as the mime type. Doing that, you can then have a @RequestParam("file") MultipartFile file
parameter on your request mapping to get a hold of the file.
I've never used Jax-RS annotations in my application, but you wouldn't even need it. Your request mapping can be as simple as this:
@RequestMapping(value ="Project/File", method = RequestMethod.POST)
public void handleFileUpload(@RequestParam("file") MultipartFile file)
Spring has a nice guide showing what you need to do for file upload if you want to see further details https://spring.io/guides/gs/uploading-files/
I should also note, you've annotated the return type of your mapping with @RequestBody
, but your return type is void
, so there's no need for @RequestBody
in this case. I'd suggest at least having a return type of HttpStatus
and then returning HttpStatus.OK
if the upload succeeded.