springmvc中multipartFile文件上传
2015-09-25 22:29
573 查看
首先准备工作:
我用的是Spring 3.02 +Gson1.71+JQuery 1.52+JQuery Uploader Pluginhttps://github.com/blueimp/jQuery-File-Upload
applicationContext.xml:
Java代码
![](http://paggywong.iteye.com/images/icon_star.png)
<!-- 激活spring的注解. -->
<context:annotation-config />
<!-- 扫描注解组件并且自动的注入spring beans中.
例如,他会扫描@Controller 和@Service下的文件.所以确保此base-package设置正确. -->
<context:component-scan base-package="com.swind.web" />
<!-- 配置注解驱动的Spring MVC Controller 的编程模型.注:次标签只在 Servlet MVC工作! -->
<mvc:annotation-driven />
dispatcher-servlet.xml
Java代码
![](http://paggywong.iteye.com/images/icon_star.png)
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>
web.xml:
Java代码
![](http://paggywong.iteye.com/images/icon_star.png)
<servlet-mapping>
<servlet-name>Dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
服务端:Controller、Service都是从网上Copy来的,加以修改。
![](http://paggywong.iteye.com/images/smiles/icon_wink.gif)
Controller:
为JQuery uploader 删除增加了一个handleDelete方法。
Java代码
![](http://paggywong.iteye.com/images/icon_star.png)
package com.swind.web.controller;
import com.google.gson.Gson;
import com.swind.common.GlobalVariable;
import com.swind.web.model.FileModel;
import com.swind.web.service.UploadService;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
@Controller
public class UploadController {
@Resource(name = "uploadService")
private UploadService uploadService;
/**
* 描述 : <事先就知道确切的上传文件数目>. <br>
*<p>
* @param file1
* @param file2
* @param model
* @return
* @throws IOException
*/
@RequestMapping(value = "/upload.single", method = RequestMethod.POST)
public
@ResponseBody
String handleImport(
@RequestParam(value = "file", required = false) MultipartFile file,
HttpServletResponse response) throws IOException {
String uploadHome = GlobalVariable.getUploadHome();
FileModel fileModel = new FileModel();
if (file != null && StringUtils.hasText(file.getOriginalFilename())) {
// System.out.println(file.getOriginalFilename());
fileModel.setName(file.getOriginalFilename());
fileModel.setSize(file.getSize());
fileModel.setType(file.getContentType());
String path = uploadService.saveFileToServer(file, uploadHome);
fileModel.setPath(path);
}
uploadService.json_encode(response, fileModel);
return null;
}
/**
* 描述 : <事先就并不知道确切的上传文件数目,比如FancyUpload这样的多附件上传组件>. <br>
*<p>
* @param model
* @param multipartRequest
* @return
* @throws IOException
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/upload.multi", method = RequestMethod.POST)
public
@ResponseBody
String handleImport(
DefaultMultipartHttpServletRequest multipartRequest,
HttpServletResponse response) throws IOException {
String uploadHome = GlobalVariable.getUploadHome();
List<FileModel> list = new ArrayList<FileModel>();
if (multipartRequest != null) {
Iterator iterator = multipartRequest.getFileNames();
while (iterator.hasNext()) {
MultipartFile multifile =
multipartRequest.getFile((String) iterator.next());
if (StringUtils.hasText(multifile.getOriginalFilename())) {
// System.out.println(multifile.getOriginalFilename());
FileModel fileModel = new FileModel();
fileModel.setName(multifile.getOriginalFilename());
fileModel.setSize(multifile.getSize());
String path = uploadService.saveFileToServer(multifile, uploadHome);
fileModel.setPath(path);
list.add(fileModel);
}
}
}
uploadService.json_encode(response, list);
return null;
}
@RequestMapping(value = "/upload.*", method = RequestMethod.DELETE)
public @ResponseBody String handleDelete(@RequestParam(value = "file", required = false) String file,
HttpServletResponse response) throws IOException {
String uploadHome = GlobalVariable.getUploadHome();
boolean success = uploadService.deleteFiletoServer(file, uploadHome);
uploadService.json_encode(response, success);
return null;
}
}
Service:
Java代码
![](http://paggywong.iteye.com/images/icon_star.png)
package com.swind.web.service;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service("uploadService")
public class UploadService {
/**
* 描述 : <将文件保存到指定路径>. <br>
*<p>
*
* @param multifile
* @param path
* @return
* @throws IOException
*/
public String saveFileToServer(MultipartFile multifile, String path)
throws IOException {
// 创建目录
File dir = new File(path);
if (!dir.exists()) {
dir.mkdir();
}
// 读取文件流并保持在指定路径
InputStream inputStream = multifile.getInputStream();
OutputStream outputStream = new FileOutputStream(path
+ multifile.getOriginalFilename());
byte[] buffer = multifile.getBytes();
int bytesum = 0;
int byteread = 0;
while ((byteread = inputStream.read(buffer)) != -1) {
bytesum += byteread;
outputStream.write(buffer, 0, byteread);
outputStream.flush();
}
outputStream.close();
inputStream.close();
return path + multifile.getOriginalFilename();
}
public boolean deleteFiletoServer(String file, String path)
throws IOException {
boolean success = Boolean.FALSE;
File f = new File(path+file);
if (f.exists()) {
f.delete();
success = Boolean.TRUE;
}
return success;
}
public void json_encode(final HttpServletResponse response, Object o) throws IOException{
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Gson gs = new Gson();
out.write(gs.toJson(o));
}
}
注;MultipartFile文件上传,若一个文件同时上传至多个目录,那么只有第一次可以被成功写入,因为MultipartFile是把文件写到内存,读取完之后自动删除的,所以第二次在读的时候,文件已经不存在了,所以上传到第N个目录应该和上传到一个目录区分开来,即第一次直接从内存读取,第二次读取第一次存取的文件
Bean:
Java代码
![](http://paggywong.iteye.com/images/icon_star.png)
package com.swind.web.model;
import java.io.Serializable;
public class FileModel implements Serializable {
/**
*
*/
private static final long serialVersionUID = 7964950152782381235L;
private String name;
private long size;
private String path;
private String type;
/**
* @return the path
*/
public String getPath() {
return path;
}
/**
* @param path the path to set
*/
public void setPath(String path) {
this.path = path;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the size
*/
public long getSize() {
return size;
}
/**
* @param size the size to set
*/
public void setSize(long size) {
this.size = size;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
HTML UPload Page:
Java代码
![](http://paggywong.iteye.com/images/icon_star.png)
<!DOCTYPE HTML>
<!--
/*
* jQuery File Upload Plugin HTML Example 4.1.2
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://creativecommons.org/licenses/MIT/
*/
-->
<html lang="en" class="no-js">
<head>
<meta charset="utf-8">
<title>jQuery File Upload Example</title>
<link rel="stylesheet" href="../res/css/themes/redmond/jquery-ui-1.8.1.custom.css" id="theme">
<link rel="stylesheet" href="../res/css/jquery.fileupload-ui.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="file_upload">
<form action="/GuzzProject/upload.multi" method="POST" enctype="multipart/form-data">
<input type="file" name="file" multiple>
<button type="submit">Upload</button>
<div class="file_upload_label">上传文件</div>
</form>
<table class="files">
<tr class="file_upload_template" style="display:none;">
<td class="file_upload_preview"></td>
<td class="file_name"></td>
<td class="file_size"></td>
<td class="file_upload_progress"><div></div></td>
<td class="file_upload_start"><button>开始</button></td>
<td class="file_upload_cancel"><button>取消</button></td>
</tr>
<tr class="file_download_template" style="display:none;">
<td class="file_download_preview"></td>
<td class="file_name"><a></a></td>
<td class="file_size"></td>
<td class="file_download_delete" colspan="3"><button>删除</button></td>
</tr>
</table>
<div class="file_upload_overall_progress"><div style="display:none;"></div></div>
<div class="file_upload_buttons">
&l
e486
t;button class="file_upload_start">全部开始</button>
<button class="file_upload_cancel">全部结束</button>
<button class="file_download_delete">全部删除</button>
</div>
</div>
<script src="../res/js/jquery-core/jquery-1.5.2.min.js"></script>
<script src="../res/js/jquery-ui/jquery-ui-1.8.1.custom.min.js"></script>
<script src="../res/js/plugin/uploader/jquery.fileupload.js"></script>
<script src="../res/js/plugin/uploader/jquery.fileupload-ui.js"></script>
<script src="../res/js/plugin/uploader/jquery.fileupload-uix.js"></script>
<script src="application.js"></script>
</body>
</html>
效果:
我用的是Spring 3.02 +Gson1.71+JQuery 1.52+JQuery Uploader Pluginhttps://github.com/blueimp/jQuery-File-Upload
applicationContext.xml:
Java代码
![](http://paggywong.iteye.com/images/icon_star.png)
<!-- 激活spring的注解. -->
<context:annotation-config />
<!-- 扫描注解组件并且自动的注入spring beans中.
例如,他会扫描@Controller 和@Service下的文件.所以确保此base-package设置正确. -->
<context:component-scan base-package="com.swind.web" />
<!-- 配置注解驱动的Spring MVC Controller 的编程模型.注:次标签只在 Servlet MVC工作! -->
<mvc:annotation-driven />
dispatcher-servlet.xml
Java代码
![](http://paggywong.iteye.com/images/icon_star.png)
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>
web.xml:
Java代码
![](http://paggywong.iteye.com/images/icon_star.png)
<servlet-mapping>
<servlet-name>Dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
服务端:Controller、Service都是从网上Copy来的,加以修改。
![](http://paggywong.iteye.com/images/smiles/icon_wink.gif)
Controller:
为JQuery uploader 删除增加了一个handleDelete方法。
Java代码
![](http://paggywong.iteye.com/images/icon_star.png)
package com.swind.web.controller;
import com.google.gson.Gson;
import com.swind.common.GlobalVariable;
import com.swind.web.model.FileModel;
import com.swind.web.service.UploadService;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
@Controller
public class UploadController {
@Resource(name = "uploadService")
private UploadService uploadService;
/**
* 描述 : <事先就知道确切的上传文件数目>. <br>
*<p>
* @param file1
* @param file2
* @param model
* @return
* @throws IOException
*/
@RequestMapping(value = "/upload.single", method = RequestMethod.POST)
public
@ResponseBody
String handleImport(
@RequestParam(value = "file", required = false) MultipartFile file,
HttpServletResponse response) throws IOException {
String uploadHome = GlobalVariable.getUploadHome();
FileModel fileModel = new FileModel();
if (file != null && StringUtils.hasText(file.getOriginalFilename())) {
// System.out.println(file.getOriginalFilename());
fileModel.setName(file.getOriginalFilename());
fileModel.setSize(file.getSize());
fileModel.setType(file.getContentType());
String path = uploadService.saveFileToServer(file, uploadHome);
fileModel.setPath(path);
}
uploadService.json_encode(response, fileModel);
return null;
}
/**
* 描述 : <事先就并不知道确切的上传文件数目,比如FancyUpload这样的多附件上传组件>. <br>
*<p>
* @param model
* @param multipartRequest
* @return
* @throws IOException
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/upload.multi", method = RequestMethod.POST)
public
@ResponseBody
String handleImport(
DefaultMultipartHttpServletRequest multipartRequest,
HttpServletResponse response) throws IOException {
String uploadHome = GlobalVariable.getUploadHome();
List<FileModel> list = new ArrayList<FileModel>();
if (multipartRequest != null) {
Iterator iterator = multipartRequest.getFileNames();
while (iterator.hasNext()) {
MultipartFile multifile =
multipartRequest.getFile((String) iterator.next());
if (StringUtils.hasText(multifile.getOriginalFilename())) {
// System.out.println(multifile.getOriginalFilename());
FileModel fileModel = new FileModel();
fileModel.setName(multifile.getOriginalFilename());
fileModel.setSize(multifile.getSize());
String path = uploadService.saveFileToServer(multifile, uploadHome);
fileModel.setPath(path);
list.add(fileModel);
}
}
}
uploadService.json_encode(response, list);
return null;
}
@RequestMapping(value = "/upload.*", method = RequestMethod.DELETE)
public @ResponseBody String handleDelete(@RequestParam(value = "file", required = false) String file,
HttpServletResponse response) throws IOException {
String uploadHome = GlobalVariable.getUploadHome();
boolean success = uploadService.deleteFiletoServer(file, uploadHome);
uploadService.json_encode(response, success);
return null;
}
}
Service:
Java代码
![](http://paggywong.iteye.com/images/icon_star.png)
package com.swind.web.service;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service("uploadService")
public class UploadService {
/**
* 描述 : <将文件保存到指定路径>. <br>
*<p>
*
* @param multifile
* @param path
* @return
* @throws IOException
*/
public String saveFileToServer(MultipartFile multifile, String path)
throws IOException {
// 创建目录
File dir = new File(path);
if (!dir.exists()) {
dir.mkdir();
}
// 读取文件流并保持在指定路径
InputStream inputStream = multifile.getInputStream();
OutputStream outputStream = new FileOutputStream(path
+ multifile.getOriginalFilename());
byte[] buffer = multifile.getBytes();
int bytesum = 0;
int byteread = 0;
while ((byteread = inputStream.read(buffer)) != -1) {
bytesum += byteread;
outputStream.write(buffer, 0, byteread);
outputStream.flush();
}
outputStream.close();
inputStream.close();
return path + multifile.getOriginalFilename();
}
public boolean deleteFiletoServer(String file, String path)
throws IOException {
boolean success = Boolean.FALSE;
File f = new File(path+file);
if (f.exists()) {
f.delete();
success = Boolean.TRUE;
}
return success;
}
public void json_encode(final HttpServletResponse response, Object o) throws IOException{
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Gson gs = new Gson();
out.write(gs.toJson(o));
}
}
注;MultipartFile文件上传,若一个文件同时上传至多个目录,那么只有第一次可以被成功写入,因为MultipartFile是把文件写到内存,读取完之后自动删除的,所以第二次在读的时候,文件已经不存在了,所以上传到第N个目录应该和上传到一个目录区分开来,即第一次直接从内存读取,第二次读取第一次存取的文件
Bean:
Java代码
![](http://paggywong.iteye.com/images/icon_star.png)
package com.swind.web.model;
import java.io.Serializable;
public class FileModel implements Serializable {
/**
*
*/
private static final long serialVersionUID = 7964950152782381235L;
private String name;
private long size;
private String path;
private String type;
/**
* @return the path
*/
public String getPath() {
return path;
}
/**
* @param path the path to set
*/
public void setPath(String path) {
this.path = path;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the size
*/
public long getSize() {
return size;
}
/**
* @param size the size to set
*/
public void setSize(long size) {
this.size = size;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
HTML UPload Page:
Java代码
![](http://paggywong.iteye.com/images/icon_star.png)
<!DOCTYPE HTML>
<!--
/*
* jQuery File Upload Plugin HTML Example 4.1.2
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://creativecommons.org/licenses/MIT/
*/
-->
<html lang="en" class="no-js">
<head>
<meta charset="utf-8">
<title>jQuery File Upload Example</title>
<link rel="stylesheet" href="../res/css/themes/redmond/jquery-ui-1.8.1.custom.css" id="theme">
<link rel="stylesheet" href="../res/css/jquery.fileupload-ui.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="file_upload">
<form action="/GuzzProject/upload.multi" method="POST" enctype="multipart/form-data">
<input type="file" name="file" multiple>
<button type="submit">Upload</button>
<div class="file_upload_label">上传文件</div>
</form>
<table class="files">
<tr class="file_upload_template" style="display:none;">
<td class="file_upload_preview"></td>
<td class="file_name"></td>
<td class="file_size"></td>
<td class="file_upload_progress"><div></div></td>
<td class="file_upload_start"><button>开始</button></td>
<td class="file_upload_cancel"><button>取消</button></td>
</tr>
<tr class="file_download_template" style="display:none;">
<td class="file_download_preview"></td>
<td class="file_name"><a></a></td>
<td class="file_size"></td>
<td class="file_download_delete" colspan="3"><button>删除</button></td>
</tr>
</table>
<div class="file_upload_overall_progress"><div style="display:none;"></div></div>
<div class="file_upload_buttons">
&l
e486
t;button class="file_upload_start">全部开始</button>
<button class="file_upload_cancel">全部结束</button>
<button class="file_download_delete">全部删除</button>
</div>
</div>
<script src="../res/js/jquery-core/jquery-1.5.2.min.js"></script>
<script src="../res/js/jquery-ui/jquery-ui-1.8.1.custom.min.js"></script>
<script src="../res/js/plugin/uploader/jquery.fileupload.js"></script>
<script src="../res/js/plugin/uploader/jquery.fileupload-ui.js"></script>
<script src="../res/js/plugin/uploader/jquery.fileupload-uix.js"></script>
<script src="application.js"></script>
</body>
</html>
效果:
![](http://dl.iteye.com/upload/attachment/472817/b2a2a972-cb55-3f03-a543-1fc5f2e22c57.jpg)
相关文章推荐
- 《Java编程思想》读书笔记4.控制执行流程
- Struts2与Struts1的对比学习(一)
- 【译】常见 Java 异常解释(恶搞版)
- Java环境变量配置
- java 通讯录
- 解决Eclipse建立Maven项目后无法建立src/main/java资源文件夹的办法
- 解决Eclipse建立Maven项目后无法建立src/main/java资源文件夹的办法
- java 基础总结
- java中的权限修饰符和修饰符
- Java语法笔记
- Struts学习之流程汇总
- Install jdk8 on Ubuntu 14.04
- java+jsp实现分页查询
- 输入年月日输出该日期是当年的第几天的java代码
- Java Web开发实战经典 实战练习2.5
- test7.17
- test7.16
- Java 反射机制
- strutsmvc ajaxForm提交表单ie出现json文件下载问题解决
- Spring MVC 解读——<mvc:annotation-driven/>