问题
I am trying to upload a Multipart File using PostMan and getting errors. Here is the code and screenshots:
http://imgur.com/pZ5cXrh
http://imgur.com/NaWQceO
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void uploadFileHandler(@RequestParam("name") String name,
@RequestParam("name") MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
//String rootPath = System.getProperty("catalina.home");
String rootPath = "C:\\Desktop\\uploads";
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
System.out.println("Server File Location="
+ serverFile.getAbsolutePath());
System.out.println("You successfully uploaded file=" + name);
} catch (Exception e) {
System.out.println("You failed to upload " + name + " => " + e.getMessage());
}
} else {
System.out.println("You failed to upload " + name
+ " because the file was empty.");
}
}
回答1:
You should have a thing like this:
@RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = "multipart/form-data")
public void uploadFileHandler(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
//String rootPath = System.getProperty("catalina.home");
String rootPath = "C:\\Users\\mworkman02\\Desktop\\uploads";
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
System.out.println("Server File Location="
+ serverFile.getAbsolutePath());
System.out.println("You successfully uploaded file=" + name);
} catch (Exception e) {
System.out.println("You failed to upload " + name + " => " + e.getMessage());
}
} else {
System.out.println("You failed to upload " + name
+ " because the file was empty.");
}
}
Please pay attention to consumes = "multipart/form-data"
. It is necessary for your uploaded file because you should have a multipart call. You should have @RequestParam("file") MultipartFile file
instead of @RequestParam("name") MultipartFile file)
.
Of course you should have configured a multipartview resolver the built-in support for apache-commons file upload and native servlet 3.
来源:https://stackoverflow.com/questions/37147395/trying-to-upload-multipartfile-with-postman