我这里写了一个单个文件上传的例子,但不知道怎么弄成多个上传,而且可以判断文件是否重复。`<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload File</title>
<link rel="stylesheet" href="/css/Lumen.css"/>
<link rel="stylesheet" href="/css/iview.css"/>
<link rel="stylesheet" href="/css/index.css"/>
<script type="text/javascript" src="/js/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/js/vue.min.js"></script>
<script type="text/javascript" src="/js/iview.min.js"></script>
<script type="text/javascript" src="/js/jyajax.js"></script>
<script type="text/javascript">
j = 1;
$(document).ready(function(){
$("#btn_add2").click(function(){
document.getElementById("newUpload2").innerHTML+='<p id="p_'+j+'"><input name="file_'+j+'" type="file" /><input type="button" value="删除" onclick="del_2('+j+')"/></p>';
j = j + 1;
});
});
function del_2(o){
document.getElementById("newUpload2").removeChild(document.getElementById("p_"+o));
}
</script>
</head>
<body style="background-color: #7aba7b;">
<hr align="left" width="60%" color="#FF0000" size="3">
<br>
<br>
<h1>springMVC包装类上传文件</h1>
<form name="userForm2" action="/file/upload2" enctype="multipart/form-data" method="post">
<p id="newUpload2">
<input type="file" name="file">
</p>
<input type="button" id="btn_add2" value="增加一行"/>
<input type="submit" value="上传"/>
</form>
<br/>
<input type="file" id="file"/>
<button type="button" class="btn btn-primary" @click="testUpload()">Click To Upload</button>
<script type="text/javascript">
var vue=new Vue({
el:'body',
data:{
pager:{
page:1,
rows:10,
totalPage:0,
totalCount:0,
},
},
methods:{
initPage:function(){
},
/* 上传文件 */
testUpload:function(){
var file=document.getElementById("file");
if(file.files.length<=0)return;
var firstFile=file.files[0];
var fd=new FormData();
fd.append('avatar',firstFile);
this.uploadAjax(fd);
},
uploadAjax:function(fd){
var xhr=new XMLHttpRequest();
xhr.open("POST","/file/uploadFile",true)
xhr.onreadystatechange=function(){
if (xhr.readyState==4 && xhr.status==200){
console.log(xhr.responseText);
alert("上传成功!");
}
};
xhr.send(fd);
},
},
ready:function(){
this.initPage();
},
});
</script>
</body>
</html>`
@Controller
@RequestMapping("file")
public class FileController {
private final static String UPLOAD="E:/file/upload/";
@RequestMapping("file")
public String toFileJsp(){
return "upLoadFile";
}
@RequestMapping("upload2")
public String uploadTwo(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException {
//创建一个通用的多部分解析器
CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
//判断 request 是否有文件上传,即多部分请求
if(multipartResolver.isMultipart(request)){
//转换成多部分request
MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
MultipartHttpServletRequest multiRequest = resolver.resolveMultipart(request);
//MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
//取得request中的所有文件名
Iterator<String> iterator=multiRequest.getFileNames();
while(iterator.hasNext()){
//记录上传过程起始时的时间,用来计算上传时间
int startTime=(int)System.currentTimeMillis();
//取得上传文件
MultipartFile file=multiRequest.getFile(iterator.next());
if(file!=null){
//取得当前上传文件的文件名称
String fileName=file.getOriginalFilename();
//如果名称不为“”,说明该文件存在,否则说明该文件不存在
if(fileName.trim() != ""){
System.out.println("文件名为:"+fileName);
//定义上传路径
String path="E:/file/"+fileName;
File localFile=new File(path);
file.transferTo(localFile);
}
}
//记录上传该文件后的时间
int endTime=(int)System.currentTimeMillis();
System.out.println("所用时间为:"+(endTime-startTime));
}
}
return "success";
}
@RequestMapping(value="uploadFile",method=RequestMethod.POST)
@ResponseBody
public Respon uploadFile(HttpServletRequest request){
MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
MultipartHttpServletRequest req = resolver.resolveMultipart(request);
Respon respon=new Respon(Constant.CODE_ERROR,Constant.CODE_ERROR_STRING);
MultipartFile file=req.getFile("avatar");
if(file.getSize()>10*1024*1024){
respon.setMsg("文件不得超过10M");
return respon;
}
String fileName=file.getOriginalFilename();
if(fileName.lastIndexOf(".")==-1){
respon.setMsg("文件异常");
return respon;
}
String ext=fileName.substring(fileName.lastIndexOf("."));
List list=Arrays.asList(new String[]{".png",".jpg",".jpeg",".bmp"});
if(!list.contains(ext.toLowerCase())){
respon.setMsg("文件格式不允许");
return respon;
}
//String base=request.getSession().getServletContext().getRealPath("/");
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
String newName=sdf.format(new Date())+"-"+UUID.randomUUID().toString()+ext;
//String parentPath=base+UPLOAD;
String parentPath=UPLOAD;
File f=new File(parentPath);
if(!f.exists()){
f.mkdirs();
}
//String fileRealPath=base+UPLOAD+newName;
String fileRealPath=UPLOAD+newName;
File f2=new File(fileRealPath);
if(f2.exists()){
f2.delete();
}
try {
file.transferTo(f2);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String webPath=UPLOAD+newName;
respon.setCode(Constant.CODE_SUCCESS);
respon.setMsg(Constant.CODE_SUCCESS_STRING);
respon.setData(webPath);
return respon;
}
}