普通的form表單提交后頁面都會跳轉(zhuǎn)击胜,可使用jQuery的ajaxSubmit來防止跳轉(zhuǎn)
需要引入jquery和jquery-from
<script type="text/javascript" src="/js/jquery/jquery.form.js"></script>
<script type="text/javascript" src="/js/jquery/jquery-1.8.0.min.js"></script>
//使用方法--提交到from表單的action
function submitForm() {
// jquery 表單提交
$("#upload").ajaxSubmit(function(message) {
// 對于表單提交成功后處理,message為表單正常提交后返回的內(nèi)容
console.log(message);
});
return false; // 必須返回false,否則表單會自己再做一次提交操作谤专,并且頁面跳轉(zhuǎn)
}
//使用方法--提交到指定的服務(wù)
function submitForm() {
var form = document.getElementById('upload'),
formData = new FormData(form);
$.ajax({
url:"http://xxxxx/fileupload",
type:"post",
data:formData,
processData:false,
contentType:false,
done: function (res) {
alert('完成了:' + res);
},
success:function(res){
if(res){
alert("上傳成功屋厘!");
}
console.log(res);
},
error:function(err){
alert("服務(wù)故障");
}
});
return false;
}
//body
<form id="fileUploadForm" action="/lzswh_gld/lyServlet" method="post" enctype="multipart/form-data">
<input name="lyid" id="lyid" hidden/>
<div class="form-group">
請選擇文件:<input id="fileFolder" name="fileFolder" type="file" /><br>
<span id="msg" style="color: #F00"></span>
</div>
<button type="button" class="btn btn-primary" id="subButton" >上傳</button>
</form>
//servlet獲取參數(shù)和文件
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
// 初始化
SmartUpload smartUpload = new SmartUpload();
ServletConfig config = this.getServletConfig();
smartUpload.initialize(config, request, response);
try {
// 上傳文件
smartUpload.upload();
// 得到上傳的文件對象
File smartFile = smartUpload.getFiles().getFile(0);
String name = smartFile.getFileName();
String type=name.substring(name.lastIndexOf("."));
String newName=System.currentTimeMillis()+"1006"+type;
// 保存文件
smartFile.saveAs(FILEPATH+newName, SmartUpload.SAVE_AUTO);
// 傳過來的注冊數(shù)據(jù)
// 只需要new SmartUpload().getRequest().getParameter(""))就能獲取到相應(yīng)的表單數(shù)據(jù)
String lyid = smartUpload.getRequest().getParameter("lyid");
System.out.println("lyid: "+lyid);
saveFile(newName,lyid,type);
writer.print(true);
} catch (SmartUploadException e) {
e.printStackTrace();
writer.print(false);
} catch (Exception e) {
e.printStackTrace();
writer.print(false);
}finally {
writer.flush();
writer.close();
}