我正在尝试使用PostMan上传Multipart文件并获取错误。以下是代码和屏幕截图:
@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.");
}
}
答案 0 :(得分:2)
你应该有这样的事情:
@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.");
}
}
请注意consumes = "multipart/form-data"
。您上传的文件是必要的,因为您应该进行多部分调用。您应该@RequestParam("file") MultipartFile file
而不是@RequestParam("name") MultipartFile file)
。
当然,您应该已经为multipartview解析程序配置了对apache-commons文件上载和本机servlet 3的内置支持。