- 同步文件上传
1、前端页面
form表单的提交方式为type=post,encytype属性值为“multipart/form-data”

input输入域的类型为type=“file”

2、后端
上传和下载的jar包
<!-- upload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
springmvc.xml文件中配置CommonsMultiPartResolver
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="#{500*1024*1024}"></property>
</bean>
目标方法的参数上使用MulTipartFile类型来接收
package com.ujiuye.pro.controller;
import com.ujiuye.pro.bean.Attachment;
import com.ujiuye.pro.bean.Project;
import com.ujiuye.pro.service.AttachmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@Controller
@RequestMapping("/attach")
public class AttachmentController {
@Autowired
private AttachmentService attachmentService;
@RequestMapping(value = "/saveInfo",method = RequestMethod.POST)
public String saveInfo(Attachment atta, MultipartFile attachment, HttpSession session){
ServletContext context=session.getServletContext();
String realPath = context.getRealPath("/upload");
File file=new File(realPath);
if(!file.exists()){
file.mkdirs();
}
//上传的文件名
String originalFilename = attachment.getOriginalFilename();
String realName=UUID.randomUUID().toString().replaceAll("-","")+originalFilename;
try {
attachment.transferTo(new File(realPath+"/"+realName));
} catch (IOException e) {
e.printStackTrace();
}
atta.setPath(realPath+"/"+realName);
attachmentService.saveInfo(atta);
return "redirect:/project-file.jsp";
}
}
- 异步文件上传
异步文件上传使用ajax并且使用Fomdata对后端传送数据
function commit(){
// $("#form2").submit();
var pid=$("#projects").val();
var attname=$("#attname").val();
var attdis=$("#attdis").val();
var remark=$("#remark").val();
//files是一个数组,在上传文件时若上传一个文件则使用files[0]
//若上传多个文件则使用files
//$("#file")[0]中的[0]是将jQuery对象转为js对象
var file=$("#file")[0].files[0];
var formdata=new FormData();
formdata.append("proFk",pid);
formdata.append("attname",attname);
formdata.append("attdis",attdis);
formdata.append("remark",remark);
formdata.append("attachment",file);
$.ajax({
type:"POST",
url:"${pageContext.request.contextPath}/attach/saveInfo",
data:formdata,
cache:false, //不要让浏览器有缓存
processData:false, //告诉浏览器,不要进行数据转换
contentType:false, //告诉浏览器,不要设置编码
success:function (msg) {
if(msg.statusCode==200){
window.location.href="${pageContext.request.contextPath}/project-file.jsp"
} else{
if (confirm("您确定要离开该页面吗?")) {
window.location.href="${pageContext.request.contextPath}/project-file.jsp"
}
}
}
});
}
</script>
</head>
<body leftmargin="8" topmargin="8" background='skin/images/allbg.gif'>
<!-- 快速转换位置按钮 -->
<table width="98%" border="0" cellpadding="0" cellspacing="1" bgcolor="#D1DDAA" align="center">
<tr>
<td height="26" background="skin/images/newlinebg3.gif">
<table width="58%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td >
当前位置:项目管理>>添加附件
</td>
</tr>
</table>
</td>
</tr>
</table>
<form name="form2" id="form2" action="${pageContext.request.contextPath}/attach/saveInfo" enctype="multipart/form-data" method="post">
<table width="98%" border="0" cellpadding="2" cellspacing="1" bgcolor="#D1DDAA" align="center" style="margin-top:8px">
<tr bgcolor="#E7E7E7">
<td height="24" colspan="2" background="skin/images/tbg.gif"> 添加附件 </td>
</tr>
<tr >
<td align="right" bgcolor="#FAFAF1" height="22">选择项目:</td>
<td align='left' bgcolor="#FFFFFF" onMouseMove="javascript:this.bgColor='#FCFDEE';" onMouseOut="javascript:this.bgColor='#FFFFFF';" height="22">
<select id="projects" name="proFk">
<option>请选择...</option>
</select>
</td>
</tr>
<tr >
<td align="right" bgcolor="#FAFAF1" height="22">附件名称:</td>
<td align='left' bgcolor="#FFFFFF" onMouseMove="javascript:this.bgColor='#FCFDEE';" onMouseOut="javascript:this.bgColor='#FFFFFF';" height="22">
<input size="26" id="attname" name="attname"/>
</td>
</tr>
<tr >
<td align="right" bgcolor="#FAFAF1" height="22">附件信息描述:</td>
<td align='left' bgcolor="#FFFFFF" onMouseMove="javascript:this.bgColor='#FCFDEE';" onMouseOut="javascript:this.bgColor='#FFFFFF';" height="22">
<input size="52" id="attdis" name="attdis"/>
</td>
</tr>
<tr >
<td align="right" bgcolor="#FAFAF1" height="22">附件:</td>
<td align='left' bgcolor="#FFFFFF" onMouseMove="javascript:this.bgColor='#FCFDEE';" onMouseOut="javascript:this.bgColor='#FFFFFF';" height="22">
<input type="file" id="file" name="attachment"/>
</td>
</tr>
<tr >
<td align="right" bgcolor="#FAFAF1" >备注:</td>
<td colspan=3 align='left' bgcolor="#FFFFFF" onMouseMove="javascript:this.bgColor='#FCFDEE';" onMouseOut="javascript:this.bgColor='#FFFFFF';" >
<textarea id="remark" rows=10 cols=130 name="remark"></textarea>
</td>
</tr>
<tr bgcolor="#FAFAF1">
<td height="28" colspan=4 align=center>
<a href="javascript:commit()" class="coolbg">保存</a>
<a href="javascript:history.go(-1)" class="coolbg">返回</a>
</td>
</tr>
</table>
</form>
后端接收跟同步文件上传大同小异
package com.ujiuye.pro.controller;
import com.ujiuye.pro.bean.Attachment;
import com.ujiuye.pro.bean.Project;
import com.ujiuye.pro.service.AttachmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@Controller
@RequestMapping("/attach")
public class AttachmentController {
@Autowired
private AttachmentService attachmentService;
@RequestMapping(value = "/saveInfo",method = RequestMethod.POST)
@ResponseBody
public Map<String,Object> saveInfo(Attachment atta, MultipartFile attachment, HttpSession session){
ServletContext context=session.getServletContext();
String realPath = context.getRealPath("/upload");
File file=new File(realPath);
if(!file.exists()){
file.mkdirs();
}
//上传的文件名
String originalFilename = attachment.getOriginalFilename();
String realName=UUID.randomUUID().toString().replaceAll("-","")+originalFilename;
try {
attachment.transferTo(new File(realPath+"/"+realName));
} catch (IOException e) {
e.printStackTrace();
}
atta.setPath(realPath+"/"+realName);
attachmentService.saveInfo(atta);
Map<String,Object> map=new HashMap<String,Object>();
map.put("statusCode",200);
map.put("message","保存成功");
return map;
}
}
本文详细介绍同步与异步文件上传的实现方法,涵盖前端表单设置、后端依赖配置及Spring MVC处理流程,深入探讨文件存储路径设定、唯一文件名生成与错误处理策略。
3066

被折叠的 条评论
为什么被折叠?



