我正在尝试创建一个RESTful控制器来上传文件。我看到了这个,并创建了以下控制器:
@RestController
public class MaterialController {
@RequestMapping(value="/upload", method= RequestMethod.POST)
public 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.";
}
}
}
然后我使用Postman发送了一个PDF文件:
但服务器崩溃并显示以下错误:
.MultipartException: Current request is not a multipart request
我再次发现了这个问题,并添加了一个bean.xml
文件。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
</beans>
很遗憾,它仍然以相同的错误抱怨。
handleFileUpload()
方法,您需要为part指定一个名称/键值为“file”。如果没有part名称,则可能没有将任何内容发送到服务器,“nothing”=“not multipart”。 - Andreas@RestController
注解类,因此您不需要在方法上注解@ResponseBody
。请参阅javadoc:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RestController.html - Andreas