问题描述
我正在将Java Web应用程序转换为Spring框架,并感谢有关文件上传所面临问题的一些建议.原始代码是使用org.apache.commons.fileupload编写的.
I am converting Java web application to Spring framework and appreciate some advice on the issues I am facing with the file upload. Original code was written using org.apache.commons.fileupload.
-
Spring MultipartFile是否包装org.apache.commons.fileupload,还是可以从我的POM文件中排除这种依赖关系?
Does Spring MultipartFile wraps org.apache.commons.fileupload or I can exclude this dependency from my POM file?
我看过以下示例:
@RequestMapping(value = "/form", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
// store the bytes somewhere
return "redirect:uploadSuccess";
} else {
return "redirect:uploadFailure";
}
}
最初,我尝试按照此示例进行操作,但是由于找不到此请求参数,总是出现错误.因此,在我的控制器中,我执行了以下操作:
Originally I tried to follow this example but was always getting an error as it couldn't find this request param. So, in my controller I have done the following:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody
ExtResponse upload(HttpServletRequest request, HttpServletResponse response)
{
// Create a JSON response object.
ExtResponse extResponse = new ExtResponse();
try {
if (request instanceof MultipartHttpServletRequest)
{
MultipartHttpServletRequest multipartRequest =
(MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFiles("file");
InputStream input = file.getInputStream();
// do the input processing
extResponse.setSuccess(true);
}
} catch (Exception e) {
extResponse.setSuccess(false);
extResponse.setMessage(e.getMessage());
}
return extResponse;
}
,它正在工作.如果有人可以告诉我为什么@RequestParam对我不起作用,我将不胜感激.顺便说一句,我确实有
and it is working. If someone can tell me why @RequestParam did not work for me, I will appreciate. BTW I do have
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="2097152"/>
</bean>
在我的servlet上下文文件中.
in my servlet context file.
推荐答案
我必须
- 将commons-fileupload依赖项添加到我的pom中,
- 添加multipartResolver bean(在问题中提到),
- 在handleFormUpload方法中使用@RequestParam("file")MultipartFile文件,并且
- 在我的jsp中添加enctype:
<form:form method="POST" action="/form" enctype="multipart/form-data" >
- add commons-fileupload dependency to my pom,
- add multipartResolver bean (mentioned in the question),
- use @RequestParam("file") MultipartFile file in the handleFormUpload method and
- add enctype in my jsp :
<form:form method="POST" action="/form" enctype="multipart/form-data" >
使其正常工作.
这篇关于Spring 3.0 MultipartFile上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!