I am trying to make a simple file upload possible but Spring does not want to play with me.
This is the endpoint for file uploads - currently not doing a lot:
Here is how i didi it:
@RequestMapping(value="/uploadFile", method=RequestMethod.POST)
public @ResponseBody String handleFileUpload(
@RequestParam("file") MultipartFile file){
String name = "test11";
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
stream.write(bytes);
stream.close();
return "You successfully uploaded " + name + " into " + name + "-uploaded !";
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name + " because the file was empty.";
}
}
and dont forget to register the multipart resolver:
@Bean
public MultipartResolver multipartResolver() {
org.springframework.web.multipart.commons.CommonsMultipartResolver multipartResolver = new org.springframework.web.multipart.commons.CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(10000000);
return multipartResolver;
}
here is the html code ... take a look at the name/id of the input fields .. File1 to upload:
Name1: <input type="text" name="name">
File2 to upload: <input type="file" name="file">
Name2: <input type="text" name="name">
<input type="submit" value="Upload"> Press here to upload the file!
</form>