1.在springmvc.xml 中配置相应的文件解析器
<!-- 文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10240000"></property>
</bean>
2. 在Controller 中上传与下载处理
上传:
/**
* 多文件文件上传处理
* 接受Android 端所传递的数据
*/
@RequestMapping(value = "/accept.do")
public void accept(HttpServletRequest request, HttpServletResponse response) throws IOException {
String realPath = request.getServletContext().getRealPath("");
String PK = request.getParameter("PK");
File file = new File(realPath + "/upload/" + PK);
if (!file.exists()) {
file.mkdirs();
}
MultipartHttpServletRequest mh = (MultipartHttpServletRequest) request;
for (int i = 0; i < FILE_NAMES.length; i++) {
MultipartFile mf = mh.getFile(FILE_NAMES[i]);
FileOutputStream fos = new FileOutputStream(realPath + "/upload/" + PK + "/" + FILE_NAMES[i] + ".json");
IOUtils.copy(mf.getInputStream(), fos);
fos.close();
}
}
下载:
/**
* PC 端的 下载处理
*/
@RequestMapping("/download.do")
public ResponseEntity<byte[]> download(HttpServletRequest request,
@RequestParam("filename") String filename,
Model model) throws Exception {
String PK = request.getParameter("PK");
filename = request.getParameter("filename");
if (StringUtils.isEmpty(PK) || StringUtils.isEmpty(filename)) {
return null;
}
String realPath = request.getServletContext().getRealPath("");
File file = new File(realPath + "/upload/" + PK + "/" + filename);
HttpHeaders headers = new HttpHeaders();
//下载显示的文件名,解决中文名称乱码问题
String downloadFielName = new String(filename.getBytes("UTF-8"), "iso-8859-1");
//通知浏览器以attachment(下载方式)打开图片
headers.setContentDispositionFormData("attachment", downloadFielName);
//application/octet-stream : 二进制流数据(最常见的文件下载)。
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
}
源码下载地址:
http://download.csdn.net/download/qq_21434959/10113352