一、配置SpringMVC
在spring.xml中配置:
<!-- springmvc文件上传需要配置的节点-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="-1"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="resolveLazily" value="false"/>
<property name="uploadTempDir" value="/statics/document/tempdir"/>
<!--<property name="maxInMemorySize" value="104857600"/>-->
</bean>
其中属性详解:
defaultEncoding="UTF-8" 是请求的编码格式,默认为iso-8859-1
maxUploadSize="-1 是上传文件的大小,单位为字节 -1表示无限制
uploadTempDir="fileUpload/temp" 为上传文件的临时路径
二、单文件与多文件上传
1、单文件上传
jsp:
<body>
<h2>文件上传实例</h2>
<form action="fileUpload.html" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="file">
<input type="submit" value="提交">
</form>
</body>
注意要在form标签中加上enctype="multipart/form-data"表示该表单是要处理文件的!
controller:
@RequestMapping("fileUpload")
public String fileUpload(@RequestParam(value = "file", required = false) MultipartFile file) {
// 判断文件是否为空
if (!file.isEmpty()) {
try {
// 文件保存路径
String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"
+ file.getOriginalFilename();
// 转存文件
file.transferTo(new File(filePath));
} catch (Exception e) {
e.printStackTrace();
}
}
// 重定向
return "redirect:/list.html";
}
注意RequestParam参数中value的名字要与jsp中的相互匹配,否则会找不到返回空指针
transferTo是存储文件的核心方法,但是这个方法同一个文件只能使用一次,不能使用第二次,否则tomcat服务器会报500的错误
MultipartFile类常用的一些方法:
- String getContentType()//获取文件MIME类型
- InputStream getInputStream()//后去文件流
- String getName() //获取表单中文件组件的名字
- String getOriginalFilename() //获取上传文件的原名
- long getSize() //获取文件的字节大小,单位byte
- boolean isEmpty() //是否为空
- void transferTo(File dest)//保存到一个目标文件中。
三、多文件上传
与上面的相同只不过是form里面多创建几个input
如果需要使用一个标签控件上传多个文件,需要使用js插件uploadify
jsp:
<body>
<h2>上传多个文件 实例</h2>
<form action="filesUpload.html" method="post"
enctype="multipart/form-data">
<p>
选择文件:<input type="file" name="files">
<p>
选择文件:<input type="file" name="files">
<p>
选择文件:<input type="file" name="files">
<p>
<input type="submit" value="提交">
</form>
</body>
controller:
private boolean saveFile(MultipartFile file) {
// 判断文件是否为空
if (!file.isEmpty()) {
try {
// 文件保存路径
String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"
+ file.getOriginalFilename();
// 转存文件
file.transferTo(new File(filePath));
return true;
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
@RequestMapping("filesUpload")
public String filesUpload(@RequestParam("files") MultipartFile[] files) {
//判断file数组不能为空并且长度大于0
if(files!=null&&files.length>0){
//循环获取file数组中得文件
for(int i = 0;i<files.length;i++){
MultipartFile file = files[i];
//保存文件
saveFile(file);
}
}
// 重定向
return "redirect:/list.html";
}
四、带参数上传
还是使用form表单进行上传,但是上传文件的时候要带上一部分的参数
例子form上传使用多个input上传多个文件并且携带参数
jsp:
其中使用了ajaxForm插件,并没有展示出来
<form method="post" enctype="multipart/form-data" id="uploadForm"
action="${pageContext.request.contextPath}/background/worksInsert">
作品名称:<input type="text" name="name" id="name"><br>
参赛年份:<input type="text" name="year" id="year"><br>
参加竞赛:<select name="competition" id="competition">
<option value="请选择">请选择</option>
</select><br>
源文件上传:<input type="file" name="file1" id="file1"><br>
展示文件上传:<input type="file" name="file2" id="file2"><br>
附件上传:<input type="file" name="file3" id="file3"><br>
<input type="submit" value="提交">
</form>
controller:
主要是参数的书写,通过不同的value取到不同得文件,同时request.getParameter方法取到参数的值
@RequestMapping("/worksInsert")
@ResponseBody
public MessageCarrier worksInsert(@RequestParam(value = "file1", required = false) MultipartFile file1, @RequestParam(value = "file2", required = false) MultipartFile file2, @RequestParam(value = "file3", required = false) MultipartFile file3, HttpServletRequest request) throws IOException {
MessageCarrier messageCarrier = new MessageCarrier();
if (file1 == null || request.getParameter("name") == null) {
return null;
}
// 获取源文件存储路径
String filename = request.getParameter("name");
String sworks = savePathL("works") + "/" + filename;
String vworks = savePathL("works") + "/" + filename;
String fworks = savePathL("works") + "/" + filename;
String sRealworks = System.getProperty("studentSystem.root") + sworks.substring(1, sworks.length());
String sRealvworks = System.getProperty("studentSystem.root") + vworks.substring(1, vworks.length());
String sRealfworks = System.getProperty("studentSystem.root") + fworks.substring(1, fworks.length());
DBWorks dbWorks = new DBWorks();
CompetitionWorks competitionWorks = new CompetitionWorks();
// System.out.println(request.getParameter("name"));
competitionWorks.setWorksName(request.getParameter("name"));
competitionWorks.setWorksYear(request.getParameter("year"));
competitionWorks.setWorksComID(request.getParameter("competition"));
competitionWorks.setWorksIsIndex("0");
competitionWorks.setWorksNeedUpdate("0");
competitionWorks.setWorksSavePath(sworks + "/" + file1.getOriginalFilename());
// 如果有展示文件获取展示文件的存储路径
if (file2 != null && file2.getSize() != 0) {
competitionWorks.setWorksSaveViewPath(vworks + "/" + file2.getOriginalFilename());
} else {
competitionWorks.setWorksSaveViewPath("NULL");
}
// 如果有附件的话获取附件的存储路径并保存
if (file3 != null && file3.getSize() != 0) {
competitionWorks.setWorksSaveFilePath(fworks + "/" + file3.getOriginalFilename());
} else {
competitionWorks.setWorksSaveFilePath("NULL");
}
//先将内容设置为NULL
competitionWorks.setWorksContent("NULL");
messageCarrier = dbWorks.worksInsert(competitionWorks);
switch (messageCarrier.getMessageContent()) {
case "OK": {
FilesUpload filesUpload = new FilesUpload();
messageCarrier = filesUpload.upload(file1, sRealworks);
if (!competitionWorks.getWorksSaveViewPath().equals("NULL")) {
messageCarrier = filesUpload.upload(file2, sRealvworks);
}
if (!competitionWorks.getWorksSaveFilePath().equals("NULL")) {
messageCarrier = filesUpload.upload(file3, sRealfworks);
}
//如果上传成功则解析内容并将其录入数据库
if (messageCarrier.getMessageContent().equals("OK")) {
String path = competitionWorks.getWorksSavePath();
String filePath = System.getProperty("studentSystem.root") + path;
String fileName = path.substring(path.lastIndexOf("/") + 1);
File file = new File(filePath);
//解析文件内容
FilesToContent filesToContent = new FilesToContent();
String content = filesToContent.resolve(file);
// System.out.println(content);
competitionWorks.setWorksContent(content);
messageCarrier = dbWorks.worksUpdateName(competitionWorks);
}
}
break;
default: {
return messageCarrier;
}
}
return messageCarrier;
}
http://fromwiz.com/share/s/3cTmX51TMQ-b2QTact03UPg83ItAml2XO4wJ23yjLa2bEKE1
时间: 2024-10-22 02:54:58