最近项目中需要上次传文档,下载文档,所以顺便的学习了下Spring MVC的上传,以及Ajax的updateFile。
准备工作:
1.与Spring MVC的配置
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
<!-- 指定所上传文件的总大小不能超过10485760000B。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>
2.引入jar包,由于项目中用到了maven,故在pom.xml进行了如下配置
<!-- 上传相关jar -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.0</version>
</dependency>
其中主要用到了commons-io-2.2以及common-fileupload-1.3.1
3.其次在jboss中添加如下配置,增加两个jar包
4.后台的配置主要如上,接下来我们使用了第三方的插件实现表单的文件传输。即:ajaxfileupload.js
在jsp中使用from表单以及input的file控件
<form id="picForm" method="post" enctype="multipart/form-data">
<span >请选择作业:</span> <input id="fileWord" name="fileWord" type="file" value="浏览..." />
</form>
页面如下图演示
本步骤中需要注意enctype="multipart/form-data" 该方式是实现文件的传输。
js中使用了如下的提交方式
$.ajaxFileUpload({
method : "POST",
// url:ctx + path, //需要链接到服务器地址
url : path,
secureuri : true,
fileElementId : 'fileWord', // 文件选择框的id属性
dataType: 'content',//返回值类型 一般设置为json
data : {
"questionId" : strquestionId,
"studentId" : strstudentId,
"teachClassId" : strteachClassId,
"answerName" : stranswerName
},
success : function(data, status) {
var reg = /<pre>(.+)<\/pre>/g;
var result = data.match(reg);
data = RegExp.$1;
alert(data);
$.messager.alert('提示','上传成功!恭祝您取得好成绩!');
},
error:function(data,status,e){
$.messager.alert('提示','提交失败!');
}
});
5.在controller(Spring MVC)的使用入下
/**
* 学生上传作业并保存作业信息
*
* @param fileWord
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/saveStudentAnswer")
public void saveStudenAnswer(
@RequestParam(value = "fileWord", required = false) MultipartFile fileWord,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String results = "error";
if (fileWord == null) {
System.out.println("fireWord为空!++++++++++++++++++");
}
StudentAnswer studentAnswer = new StudentAnswer();
String answerName = request.getParameter("answerName");
String dataBaseName = "itoo_basic";
/* 获取当前时间 */
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String answerTime = df.format(date);
String questionId = request.getParameter("questionId");
// String operator = request.getParameter("123");
String studentId = request.getParameter("studentId");
String teachClassId = request.getParameter("teachClassId");
String studentAnswerId = studentAnswerBean.queryStudentAnswerByHql(
studentId, questionId, teachClassId, dataBaseName);
// 获取上传的文件
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file1 = multipartRequest.getFile("fileWord");
String fileName = fileWord.getOriginalFilename();
String logoRealPathDir = request.getSession().getServletContext()
.getRealPath(fileName);
File localFile = new File(logoRealPathDir);
try {
file1.transferTo(localFile);
} catch (IllegalStateException | IOException e) {
System.out.printf(
"StudentAnswerController中file1.transferTo调用失败: %s%n",
e.getMessage());
}
// 将获取的参数保存到studentAnswer实体更新数据库
studentAnswer.setAnswerName(answerName);
studentAnswer.setDataBaseName(dataBaseName);
studentAnswer.setAnswerTime(answerTime);
studentAnswer.setQuestionId(questionId);
studentAnswer.setIsDelete(0);
studentAnswer.setOperator("lxy");
studentAnswer.setStudentId(studentId);
studentAnswer.setTeachClassId(teachClassId);
StudentAnswer answer = studentAnswerBean
.saveStudentAnswer(studentAnswer);
if (answer != null) {
String wordId = answer.getId();
// 将文档上传到mongo数据库中
LinkedHashMap map = new LinkedHashMap();
String dbName = "itooresult";
String collectionName = "answer";
MongoUtil mongoUtil = new MongoUtil();
// 将图片保存到mongo中
try {
mongoUtil.uploadFile(localFile, wordId, dbName,
collectionName, map);
} catch (Exception e) {
System.out.printf("StudentAnswerController中saveStudenAnswer里mongoUtil.uploadFile调用 方法失败: %s%n",e.getMessage());
}
// 如果上传的文件成功,则将上传的文件在服务器中删除,防止服务器中文件导致服务器内存变小
if (localFile.isFile()) {
localFile.delete();
}
}
results = "success";
jacksonJsonUntil.beanToJson(response, results);
}
实践中成长!