java的文件上传,采用的springmvc作为表示层。主要注意以下几点:
1.application.xml中 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>的配置,我们上传基本上都采用这个对象,避免了我们直接对流进行操作
2.第二步,没有避免中文乱码问题,有个简便的写法:在web.xml中配置:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
其实这一步就是request.setCharacterEncoding("utf-8")和response.setCharacterEncoding("utf-8")的意思。
3.第三步:
public Result fileUpload(HttpServletRequest request,@RequestParam(value = "file",required=false)MultipartFile file){ String path = request.getSession().getServletContext().getRealPath("upload");
String fileName = file.getOriginalFilename();
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
return new ErrorResult(e);
}
}
以上就可完成上传了。