基於html5的檔案上傳案例
阿新 • • 發佈:2018-12-23
html5的formData物件可以向正常的form表單一樣通過ajax請求傳送,包括上傳檔案並且可以一次性上傳多個檔案。並且可以根據監聽事件,監視上傳進度,終止,結束等等。下面的例項程式碼使用到了bootstrap,跑的話先搭建好bootstrap環境。並且要支援html5的瀏覽器。
jsp頁面程式碼
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<link rel="stylesheet" href="${pageContext.request.contextPath }/bootstrap.css">
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<div class="navbar-brand">
HellpPeng
</div>
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
aria-expanded="true" aria-controls="navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="#">上傳檔案</a></li>
</ul>
</div>
</div>
</nav>
<div class="container center-block" style="width:60%; max-width: 600px; margin-top: 100px;">
<form id="form1" class="form-horizontal" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label class=" col-sm-3" for="fileName">檔名稱</label>
<input class="form-control " type="text" id="fileName" name="fileName" style="max-width: 250px;" disabled="disabled">
</div>
<div class="form-group">
<label class="col-sm-3">檔案型別</label>
<input type="text" class="form-control" id="fileType" name="fileType" style="max-width: 200px;" disabled="disabled">
</div>
<div class="form-group">
<label class="col-sm-4" >檔案大小</label>
<input id="fileSize" type="text" class="form-control" name="fileSize" style="max-width: 200px;" disabled="disabled">
</div>
<div class="form-group">
<label class="col-sm-4 " for="upFile">選擇檔案</label>
<div>
<input style="opacity: 0; position: absolute;" type="file" id="upFile" name="file" onchange="fileSelect()" multiple="multiple">
<label class="label label-danger" style="font-size: 1em">點選上傳圖片</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-3" for="name">上傳者</label>
<input class="form-control " type="text" name="name" id="name">
</div>
<div class="form-group">
<label id="progress" class=col-sm-3">上傳進度</label>
<div class="progress">
<div class="progress-bar progress-bar-success" style="width: 0%;"></div>
</div>
</div>
<div class="form-group text-center">
<input type="button" class="btn-lg btn btn-primary col-sm-3" style="margin: 10px;" onclick="uploadFile()" value="提交">
<input type="button" class="btn-lg btn btn-warning col-sm-3" style="margin: 10px;" onclick="cancleUploadFile()" value="取消">
</div>
</form>
</div>
<script src="${pageContext.request.contextPath }/jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath }/bootstrap.min.js" type="text/javascript"></script>
</body>
<script type="text/javascript">
var ajax = new XMLHttpRequest();
//檔案上傳
function uploadFile(){
//通過form1表單構建FormData物件
var fd = new FormData(document.getElementById("form1"));
//新增引數
// fd.append("dd",$("#fileName").val())
// fd.append("fileName",$("#upFile")[0].files[0]);
//新增上傳事件
ajax.upload.addEventListener("progress",uploadProgress,false);
ajax.addEventListener("load",uploadComplete,false);
ajax.addEventListener("error",uploadFailed,false);
ajax.addEventListener("abort",uploadCanaeled,false);
//請求地址
ajax.open("POST","http://localhost:8080/st/demo7.action");
ajax.send(fd);
}
//上傳進度evt.loaded已讀取位元組 evt.total總位元組大小
function uploadProgress(evt){
if(evt.lengthComputable){
var percentComplete = Math.round(evt.loaded*100/evt.total);
$("#progress").text("上傳進度"+percentComplete+"%");
$(".progress-bar.progress-bar-success").css("width",percentComplete+"%");
}
}
//取消上傳
function cancleUploadFile(){
alert("取消");
ajax.abort();
}
//上傳成功響應
function uploadComplete(evt){
alert(evt.target.responseText);
}
//上傳失敗
function uploadFailed(evt){
alert("上傳失敗!");
alert(evt.target.responseText);
}
//取消上傳
function uploadCanaeled(evt){
alert("取消上傳!");
alert(evt.target.responseText);
}
//選擇檔案後顯示在input框
function fileSelect(){
var file = $("#upFile")[0].files[0];
if(file){
var fileSize = 0;
if(file.size > 1024*1024)
fileSize = (Math.round(file.size*100/(1024*1024)/100).toString()+"MB");
else
fileSize = (Math.round(file.size*100/1024).toString()+"KB");
$("#fileSize").val(fileSize);
$("#fileName").val(file.name);
$("#fileType").val(file.type);
//$("#image").attr("src", $("#upFile").val()) ;
}
}
</script>
</html>
伺服器部分:
因為是案例就隨便將工程建立在了struts2環境上面了但是使用的是fileUpload.jar包的源生寫法,因為request物件經過struts2的封裝,如果直接使用parseRequest()方法直接解析request物件是解析不到任何資料的。所以為了解決這個問題,我們需要將struts2對request物件的封裝取消。
首先在struts2的配置檔案中新增以下語句(好像struts2.3.4以前的版本需要改變繼承的包):
<bean type= "org.apache.struts2.dispatcher.multipart.MultiPartRequest"
name= "myRequestParser" class= "com.ljp.struts.Demo6"
scope= "default" optional= "true " />
<constant name="struts.multipart.parser" value= "myRequestParser" />
之後在制定的java檔案裡面覆蓋struts2的原本方法:
@Override
public void parse(HttpServletRequest request, String saveDir)throws IOException {
// TODO Auto-generated method stub
}經過這些步驟之後就可以實現伺服器端的操作了
struts.xml
jsp頁面程式碼
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<link rel="stylesheet" href="${pageContext.request.contextPath }/bootstrap.css">
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<div class="navbar-brand">
HellpPeng
</div>
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
aria-expanded="true" aria-controls="navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="#">上傳檔案</a></li>
</ul>
</div>
</div>
</nav>
<div class="container center-block" style="width:60%; max-width: 600px; margin-top: 100px;">
<form id="form1" class="form-horizontal" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label class=" col-sm-3" for="fileName">檔名稱</label>
<input class="form-control " type="text" id="fileName" name="fileName" style="max-width: 250px;" disabled="disabled">
</div>
<div class="form-group">
<label class="col-sm-3">檔案型別</label>
<input type="text" class="form-control" id="fileType" name="fileType" style="max-width: 200px;" disabled="disabled">
</div>
<div class="form-group">
<label class="col-sm-4" >檔案大小</label>
<input id="fileSize" type="text" class="form-control" name="fileSize" style="max-width: 200px;" disabled="disabled">
</div>
<div class="form-group">
<label class="col-sm-4 " for="upFile">選擇檔案</label>
<div>
<input style="opacity: 0; position: absolute;" type="file" id="upFile" name="file" onchange="fileSelect()" multiple="multiple">
<label class="label label-danger" style="font-size: 1em">點選上傳圖片</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-3" for="name">上傳者</label>
<input class="form-control " type="text" name="name" id="name">
</div>
<div class="form-group">
<label id="progress" class=col-sm-3">上傳進度</label>
<div class="progress">
<div class="progress-bar progress-bar-success" style="width: 0%;"></div>
</div>
</div>
<div class="form-group text-center">
<input type="button" class="btn-lg btn btn-primary col-sm-3" style="margin: 10px;" onclick="uploadFile()" value="提交">
<input type="button" class="btn-lg btn btn-warning col-sm-3" style="margin: 10px;" onclick="cancleUploadFile()" value="取消">
</div>
</form>
</div>
<script src="${pageContext.request.contextPath }/jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath }/bootstrap.min.js" type="text/javascript"></script>
</body>
<script type="text/javascript">
var ajax = new XMLHttpRequest();
//檔案上傳
function uploadFile(){
//通過form1表單構建FormData物件
var fd = new FormData(document.getElementById("form1"));
//新增引數
// fd.append("dd",$("#fileName").val())
// fd.append("fileName",$("#upFile")[0].files[0]);
//新增上傳事件
ajax.upload.addEventListener("progress",uploadProgress,false);
ajax.addEventListener("load",uploadComplete,false);
ajax.addEventListener("error",uploadFailed,false);
ajax.addEventListener("abort",uploadCanaeled,false);
//請求地址
ajax.open("POST","http://localhost:8080/st/demo7.action");
ajax.send(fd);
}
//上傳進度evt.loaded已讀取位元組 evt.total總位元組大小
function uploadProgress(evt){
if(evt.lengthComputable){
var percentComplete = Math.round(evt.loaded*100/evt.total);
$("#progress").text("上傳進度"+percentComplete+"%");
$(".progress-bar.progress-bar-success").css("width",percentComplete+"%");
}
}
//取消上傳
function cancleUploadFile(){
alert("取消");
ajax.abort();
}
//上傳成功響應
function uploadComplete(evt){
alert(evt.target.responseText);
}
//上傳失敗
function uploadFailed(evt){
alert("上傳失敗!");
alert(evt.target.responseText);
}
//取消上傳
function uploadCanaeled(evt){
alert("取消上傳!");
alert(evt.target.responseText);
}
//選擇檔案後顯示在input框
function fileSelect(){
var file = $("#upFile")[0].files[0];
if(file){
var fileSize = 0;
if(file.size > 1024*1024)
fileSize = (Math.round(file.size*100/(1024*1024)/100).toString()+"MB");
else
fileSize = (Math.round(file.size*100/1024).toString()+"KB");
$("#fileSize").val(fileSize);
$("#fileName").val(file.name);
$("#fileType").val(file.type);
//$("#image").attr("src", $("#upFile").val()) ;
}
}
</script>
</html>
伺服器部分:
因為是案例就隨便將工程建立在了struts2環境上面了但是使用的是fileUpload.jar包的源生寫法,因為request物件經過struts2的封裝,如果直接使用parseRequest()方法直接解析request物件是解析不到任何資料的。所以為了解決這個問題,我們需要將struts2對request物件的封裝取消。
首先在struts2的配置檔案中新增以下語句(好像struts2.3.4以前的版本需要改變繼承的包):
<bean type= "org.apache.struts2.dispatcher.multipart.MultiPartRequest"
name= "myRequestParser" class= "com.ljp.struts.Demo6"
scope= "default" optional= "true " />
<constant name="struts.multipart.parser" value= "myRequestParser" />
之後在制定的java檔案裡面覆蓋struts2的原本方法:
@Override
public void parse(HttpServletRequest request, String saveDir)throws IOException {
// TODO Auto-generated method stub
}經過這些步驟之後就可以實現伺服器端的操作了
struts.xml