我在這裡寫(xiě)了一個(gè)單一檔案上傳的例子,但不知道怎麼弄成多個(gè)上傳,而且可以判斷檔案是否重複。 `<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<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>
<hr align="left" width="60%" color="#FF0000" size="3">
<br>
<br>
<h1>springMVC包裝類(lèi)上傳文件</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>
`
@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 {
//創(chuàng)建一個(gè)通用的多部分解析器
CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
//判斷 request 是否有文件上傳,即多部分請(qǐng)求
if(multipartResolver.isMultipart(request)){
//轉(zhuǎn)換成多部分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()){
//記錄上傳過(guò)程起始時(shí)的時(shí)間,用來(lái)計(jì)算上傳時(shí)間
int startTime=(int)System.currentTimeMillis();
//取得上傳文件
MultipartFile file=multiRequest.getFile(iterator.next());
if(file!=null){
//取得當(dāng)前上傳文件的文件名稱(chēng)
String fileName=file.getOriginalFilename();
//如果名稱(chēng)不為“”,說(shuō)明該文件存在,否則說(shuō)明該文件不存在
if(fileName.trim() != ""){
System.out.println("文件名為:"+fileName);
//定義上傳路徑
String path="E:/file/"+fileName;
File localFile=new File(path);
file.transferTo(localFile);
}
}
//記錄上傳該文件后的時(shí)間
int endTime=(int)System.currentTimeMillis();
System.out.println("所用時(shí)間為:"+(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("文件不得超過(guò)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;
}
}