java 使用 Spring MVC 将文件上传到服务器目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14101558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
File Upload to Server Directory Using Spring MVC
提问by schoolcoder
I am trying to upload a file to the server directory from client machine. I used the following codes :
我正在尝试从客户端计算机将文件上传到服务器目录。我使用了以下代码:
FileUpload.jsp
文件上传.jsp
<form:form commandName="fileUpload" action="upload.action" method="post" enctype="multipart/form-data">
<form:label path="fileData">Upload a File</form:label> <br />
<form:input type="file" path="fileData" />
<input type="submit" value="upload" >
</form:form>
In my Controller:
在我的控制器中:
@RequestMapping("/upload.action")
public String upload(@ModelAttribute("fileUpload") FileUpload fileUpload,HttpServletResponse response,Model model)
{
CommonsMultipartFile multipartFile = fileUpload.getFileData();
String orginalName = multipartFile.getOriginalFilename();
String filePath = "/my_uploads/"+orginalName;
File destination = new File(filePath);
String status ="success";
try {
multipartFile.transferTo(destination);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
status="failure";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
status="iofailure";
}
model.addAttribute("status", status);
return "home";
}
FileUpload.java :
文件上传.java :
{
private CommonsMultipartFile fileData;
....
}
NullPointerException
is thrown at the line String orginalName = multipartFile.getOriginalFilename();
.. what wrong thing i have done??
NullPointerException
被扔在了线上String orginalName = multipartFile.getOriginalFilename();
..我做错了什么??
回答by Kevin Bowersox
Try adding the MultipartFile
as a parameter in your requesthandler.
尝试MultipartFile
在请求处理程序中添加作为参数。
@RequestMapping("/upload.action")
public String upload(@RequestParam(value = "file") MultipartFile file,
HttpServletResponse response,Model model)
{
//Controller logic...
}
This will require you to register a new bean in your dispatcher's configuration.
这将要求您在调度程序的配置中注册一个新 bean。
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000"/>
</bean>
回答by Darshan
@RequestMapping("/upload.action")
public String upload(@RequestParam("fileData") MultipartFile file,
HttpServletResponse response,Model model)
{
//Controller logic...
}
you should have the same name in the parameter for your request handler method ,whatever you given in the FileUpload Pojo for multipartFile ("fileData") it should be in the parameter
您应该在请求处理程序方法的参数中具有相同的名称,无论您在 FileUpload Pojo 中为 multipartFile ("fileData") 提供什么,它都应该在参数中
Thanks,
谢谢,