重慶分公司,新征程啟航
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊(cè)、服務(wù)器等服務(wù)
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊(cè)、服務(wù)器等服務(wù)
本篇文章是對(duì)Jquery中的LigerUI實(shí)現(xiàn)文件上傳的方法,進(jìn)行了分析介紹,需要的朋友可以參考下
創(chuàng)新互聯(lián)公司是一家集網(wǎng)站建設(shè),肅南裕固族自治企業(yè)網(wǎng)站建設(shè),肅南裕固族自治品牌網(wǎng)站建設(shè),網(wǎng)站定制,肅南裕固族自治網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,肅南裕固族自治網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競(jìng)爭(zhēng)力。可充分滿足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶成長(zhǎng)自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。
一、在Head中加入
script src="../lib/js/ajaxfileupload.js" type="text/javascript"/script
script src="../lib/js/ligerui.expand.js" type="text/javascript"/script
二、Html中的Div代碼
復(fù)制代碼 代碼如下:
div id="AppendBill_Div" style="display:none;" %-- 上傳 - 單 --%
table style="height:100%;width:100%"
tr style="height:40px"
td style="width:20%"
圖標(biāo):
/td
tdinput type="file" style="width:200px" id="fileupload" name="fileupload"/
/td
/tr
/table
/div
三、Js中-寫的是關(guān)鍵部分,會(huì)LigerUI的朋友-你懂得
1、grid中添加項(xiàng)【存地址字段】
{ display: "掃描件", name: "AppendBillPath", width: 120, type: "text", align: "left" }
2、Form可添加項(xiàng)【存地址和彈出選擇框】
{ name: "AppendBillPath1", type: "hidden" }, // --上傳-【5】--
{ display: "掃描件", name: "AppendBillPath", comboboxName: "AppendBillPath2", newline: true, labelWidth: 100, width: 150, space: 30, type: "select", options: {}} // --上傳-【6】--
$.ligerui.get("AppendBillPath2").set('onBeforeOpen', f_selectAppendBillPath_1) // 【掃描件】 // --上傳-【7】--
3、事件
// #region ======================================= 【上傳掃描件窗口】 // --上傳-【8】--
復(fù)制代碼 代碼如下:
var AppendBillPathDetail = null;
function f_selectAppendBillPath_1() {
var imageurl = $("#AppendBill").val();
var AppendBill_Id = $("#AppendBill").val(); // 單號(hào)
if (imageurl.length == 0) {
LG.showError("您沒有輸入單號(hào),請(qǐng)輸入隨單號(hào)!");
return;
}
if (AppendBillPathDetail) {
AppendBillPathDetail.show();
}
else {
AppendBillPathDetail = $.ligerDialog.open({
target: $("#AppendBill_Div"), title: '添加圖標(biāo)',
width: 360, height: 170, top: 170, left: 280, // 彈出窗口大小
buttons: [
{ text: '上傳', onclick: function () { AppendBillPath_save(); } },
{ text: '取消', onclick: function () { AppendBillPathDetail.hide(); } }
]
});
}
}
function AppendBillPath_save()
{
var imgurl = $("#fileupload").val();
// var filehelpcode = $("#filehelpcode").val();
var extend = imgurl.substring(imgurl.lastIndexOf("."), imgurl.length);
extend = extend.toLowerCase();
if (extend == ".jpg" || extend == ".jpeg" || extend == ".png" || extend == ".gif" || extend == ".bmp")
{
}
else
{
LG.showError("請(qǐng)上傳jpg,jpep,png,gif,bmp格式的圖片文件");
return;
}
var imageurl = $("#AppendBill").val(); // extend
alert(imageurl);
$.ajaxFileUpload({
url: "../handle/ImageUpload.aspx?imageurl=" + imageurl, // --上傳-【9】-- aspx文件
secureuri: false,
fileElementId: "fileupload", //Input file id
dataType: "text",
success: function (data, status)
{
// ----------------- // 保存路徑
// $("#AppendBillPath2").val(Data);
LG.tip(data);
f_reload();
},
error: function (data, status, e) {
LG.showError(data);
}
});
}
// #endregion
四、后臺(tái)cs,寫一句關(guān)鍵的,可以返回參數(shù),前臺(tái)提示
string url = Server.MapPath("/Image/" + gfilename + filenameext); // 執(zhí)行上傳操作
ajax的表單提交只能提交data數(shù)據(jù)到后臺(tái),沒法實(shí)現(xiàn)file文件的上傳還有展示進(jìn)度功能,這里用到form.js的插件來實(shí)現(xiàn),搭配css樣式簡(jiǎn)單易上手,而且高大上,推薦使用。
需要解釋下我的結(jié)構(gòu), #upload-input-file 的input標(biāo)簽是真實(shí)的文件上傳按鈕,包裹form標(biāo)簽后可以實(shí)現(xiàn)上傳功能, #upload-input-btn 的button標(biāo)簽是展示給用戶的按鈕,因?yàn)樾枰獦邮降拿阑I蟼魍瓿缮傻奈募麑?huì)顯示在 .upload-file-result 里面, .progress 是進(jìn)度條的位置,先讓他隱藏加上 hidden 的class, .progress-bar 是進(jìn)度條的主體, .progress-bar-status 是進(jìn)度條的文本提醒。
去掉hidden的class,看到的效果是這樣的
[圖片上傳失敗...(image-2c700a-1548557865446)]
將上傳事件綁定在file的input里面,綁定方式就隨意了。
var progress = $(".progress-bar"), status = $(".progress-bar-status"), percentVal = '0%'; //上傳步驟 $("#myupload").ajaxSubmit({ url: uploadUrl, type: "POST", dataType: 'json', beforeSend: function () { $(".progress").removeClass("hidden"); progress.width(percentVal); status.html(percentVal); }, uploadProgress: function (event, position, total, percentComplete) { percentVal = percentComplete + '%'; progress.width(percentVal); status.html(percentVal); console.log(percentVal, position, total); }, success: function (result) { percentVal = '100%'; progress.width(percentVal); status.html(percentVal); //獲取上傳文件信息 uploadFileResult.push(result); // console.log(uploadFileResult); $(".upload-file-result").html(result.name); $("#upload-input-file").val(''); }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(errorThrown); $(".upload-file-result").empty(); } });
[圖片上傳失敗...(image-3d6ae0-1548557865446)]
[圖片上傳失敗...(image-9f0adf-1548557865446)]
更多用法可以 參考官網(wǎng)
/*?jQuery實(shí)現(xiàn)文件上傳,參考例子如下:
package?com.kinth.hddpt.file.action;??
import?java.io.File;??
import?java.io.FileNotFoundException;??
import?java.io.FileOutputStream;??
import?java.io.IOException;??
import?java.io.InputStream;??
import?java.io.OutputStream;??
import?java.util.ArrayList;??
import?java.util.Calendar;??
import?java.util.Enumeration;??
import?java.util.Hashtable;??
import?java.util.List;??
import?javax.servlet.http.HttpServletRequest;??
import?javax.servlet.http.HttpServletResponse;??
import?net.sf.json.JSONArray;??
import?org.apache.commons.logging.Log;??
import?org.apache.commons.logging.LogFactory;??
import?org.apache.struts.action.ActionForm;??
import?org.apache.struts.action.ActionForward;??
import?org.apache.struts.action.ActionMapping;??
import?org.apache.struts.upload.FormFile;??
import?org.hibernate.criterion.MatchMode;??
import?org.hibernate.criterion.Order;??
import?org.hibernate.criterion.Restrictions;??
import?com.gdcn.bpaf.common.base.search.MyCriteria;??
import?com.gdcn.bpaf.common.base.search.MyCriteriaFactory;??
import?com.gdcn.bpaf.common.base.service.BaseService;??
import?com.gdcn.bpaf.common.helper.PagerList;??
import?com.gdcn.bpaf.common.helper.WebHelper;??
import?com.gdcn.bpaf.common.taglib.SplitPage;??
import?com.gdcn.bpaf.security.model.LogonVO;??
import?com.gdcn.components.appauth.common.helper.DictionaryHelper;??
import?com.kinth.common.base.action.BaseAction;??
import?com.kinth.hddpt.file.action.form.FileCatalogForm;??
import?com.kinth.hddpt.file.model.FileCatalog;??
import?com.kinth.hddpt.file.service.FileCatalogService;??
import?com.kinth.hddpt.file.util.MyZTreeNode;??
/**?
*?p?
*?description:?“文件上傳的Struts層請(qǐng)求處理類”?
*?/p?
*?@date?:?2013-1-14?
*/??
public?class?FileCatalogAction?extends?BaseActionFileCatalog?{??
@SuppressWarnings("unused")??
private?static?Log?log?=?LogFactory.getLog(FileCatalogAction.class);?//?日志記錄??
private?FileCatalogService?fileCatalogService;??
//?刪除記錄的同時(shí)刪除相應(yīng)文件??
public?ActionForward?fileDelete(ActionMapping?mapping,?ActionForm?form,??
HttpServletRequest?request,?HttpServletResponse?response)??
throws?Exception?{??
String[]?id?=?request.getParameterValues("resourceId");??
if?(id?!=?null??id[0].contains(","))?{??
id?=?id[0].split(",");??
}??
String[]?fileUrls?=?new?String[id.length];??
for?(int?j?=?0;?j??id.length;?j++)?{??
fileUrls[j]?=?fileCatalogService.findObject(id[j]).getFileUrl();??
if?(!isEmpty(fileUrls[j]))?{??
//?如果該文件夾不存在則創(chuàng)建一個(gè)uptext文件夾??
File?fileup?=?new?File(fileUrls[j]);??
if?(fileup.exists()?||?fileup?!=?null)?{??
fileup.delete();??
}??
}??
fileCatalogService.deleteObject(id[j]);??
}??
setAllActionInfos(request);??
return?list(mapping,?form,?request,?response);??
}??
@Override??
public?ActionForward?save(ActionMapping?mapping,?ActionForm?form,??
HttpServletRequest?request,?HttpServletResponse?response)??
throws?Exception?{??
String?id?=?request.getParameter("resourceId");???
Boolean?fileFlag?=?Boolean.valueOf(request.getParameter("fileFlag"));??
if(fileFlag?!=?null??fileFlag?==?true){??
return?super.save(mapping,?form,?request,?response);??
}else{??
String?fileUrl?=?this.fileUpload(form,?request,?id,?fileFlag);??
response.setContentType("text/html");??
response.setCharacterEncoding("GBK");??
response.setHeader("Charset",?"GBK");??
response.setHeader("Cache-Control",?"no-cache");??
response.getWriter().write(fileUrl);??
response.getWriter().flush();??
}??
return?null;??
}??
@SuppressWarnings("unchecked")??
public?String?fileUpload(ActionForm?form,HttpServletRequest?request,String?id,Boolean?fileFlag)?throws?FileNotFoundException,?IOException{??
request.setCharacterEncoding("GBK");??
String?basePath?=?getServlet().getServletConfig().getServletContext().getRealPath("")+"/";??
String?filePath?=?"uploads/";?//?獲取項(xiàng)目根路徑????;??
/*注釋部分對(duì)應(yīng)jquery?upload?uploadify插件的后臺(tái)代碼,只是還存在編碼問題,默認(rèn)為utf-8?
String?savePath?=?getServlet().getServletConfig().getServletContext().getRealPath("");?//?獲取項(xiàng)目根路徑?
savePath?=?savePath?+?"\\uploads\\";?
//讀取上傳來的文件信息?
HashtableString,?FormFile?fileHashtable?=?form.getMultipartRequestHandler().getFileElements();?
EnumerationString?enumeration?=?fileHashtable.keys();?
enumeration.hasMoreElements();?
String?key?=?(String)?enumeration.nextElement();?
FormFile?formFile?=?(FormFile)fileHashtable.get(key);?
String?filename?=?formFile.getFileName().trim();?//文件名?
filename?=?new?EncodeChange().changeCode(filename);?
String?filetype?=?filename.substring(filename.lastIndexOf(".")?+?1);//文件類型?
savePath?=?savePath+filetype+"\\";?
System.out.println("path:"+savePath);?
String?realPath?=?savePath?+??filename;?//真實(shí)文件路徑?
//如果該文件夾不存在則創(chuàng)建一個(gè)文件夾?
File?fileup?=?new?File(savePath);?
if(!fileup.exists()||fileup==null){?
fileup.mkdirs();?
}?
if?(!filename.equals(""))?{?
//?在這里上傳文件?
InputStream?is?=?formFile.getInputStream();?
OutputStream?os?=?new?FileOutputStream(realPath);?
int?bytesRead?=?0;?
byte[]?buffer?=?new?byte[8192];?
while?((bytesRead?=?is.read(buffer,?0,?8192))?!=?-1)?{?
os.write(buffer,?0,?bytesRead);?
}?
os.close();?
is.close();?
//如果是修改操作,則刪除原來的文件?
String?id?=?request.getParameter("resourceId");?
if?(!isEmpty(id))?{?
FileCatalog?fileCatalog?=?fileCatalogService.findObject(id);?
String?fileUrl?=?fileCatalog.getFileUrl();?
if?(!isEmpty(fileUrl))?{?
File?filedel?=?new?File(fileUrl);?
if(filedel.exists()||filedel!=null){?
filedel.delete();?
}?
}?
request.setAttribute("entity",?fileCatalog);?
}?
response.getWriter().print(realPath);//?向頁面端返回結(jié)果信息?
}*/??
//?讀取上傳來的文件信息??
HashtableString,?FormFile?fileHashtable?=?form.getMultipartRequestHandler().getFileElements();??
EnumerationString?enumeration?=?fileHashtable.keys();??
enumeration.hasMoreElements();??
String?key?=?(String)?enumeration.nextElement();??
FormFile?formFile?=?(FormFile)?fileHashtable.get(key);??
String?filename?=?formFile.getFileName().trim();?//?文件名??
String?filetype?=?filename.substring(filename.lastIndexOf(".")?+?1);//?文件類型???????
Integer?fileSize?=?formFile.getFileSize();??
filePath?+=?Calendar.getInstance().get(Calendar.YEAR)+"/"+filetype+"/"?;??
String?realPath?=?basePath+filePath+filename;??//?真實(shí)文件路徑??
if?(!filename.equals(""))?{??
//?如果是修改操作,則刪除原來的文件??
if?(!isEmpty(id))?{??
FileCatalog?fileCatalog?=?fileCatalogService.findObject(id);??
String?fileUrl?=?fileCatalog.getFileUrl();??
if?(!isEmpty(fileUrl))?{??
fileUrl?=?basePath?+?fileUrl;??
File?filedel?=?new?File(fileUrl);??
if?(filedel.exists()?||?filedel?!=?null)?{??
filedel.delete();??
}??
}??
request.setAttribute("entity",?fileCatalog);??
}??
//?如果該文件夾不存在則創(chuàng)建一個(gè)文件夾??
File?fileup?=?new?File(basePath+filePath);??
if?(!fileup.exists()?||?fileup?==?null)?{??
fileup.mkdirs();??
}??
//?在這里上傳文件??
InputStream?is?=?formFile.getInputStream();??
OutputStream?os?=?new?FileOutputStream(realPath);??
int?bytesRead?=?0;??
byte[]?buffer?=?new?byte[8192];??
while?((bytesRead?=?is.read(buffer,?0,?8192))?!=?-1)?{??
os.write(buffer,?0,?bytesRead);??
}??
os.close();??
is.close();??
}??
filePath?+=?filename;??
String?result?=?"{\"fileName\":\""+filename+"\",\"fileType\":\""+filetype+"\",\"fileSize\":"+fileSize+",\"fileUrl\":\""+filePath+"\"}";???????????
return?result;??
}??
public?FileCatalogService?getFileCatalogService()?{??
return?fileCatalogService;??
}??
public?void?setFileCatalogService(FileCatalogService?fileCatalogService)?{??
this.fileCatalogService?=?fileCatalogService;??
}??
}
使用方法:
1. 需要加載的js文件:
jquey-1.8.3.min.js
jquery-ui-widget.js
jquery.iframe-transport.js
jquery.fileupload.js
2. html代碼:
?
1
input id="fileupload" type="file" name="files[]" data-url="server/php/" multiple
3. js代碼:
?
12345678910
$(function () {$('#fileupload').fileupload({dataType: 'json',done: function (e, data) {$.each(data.result.files, function (index, file) {$('p/').text(file.name).appendTo(document.body);});}});});
3.1 顯示上傳進(jìn)度條:
?
123456789
$('#fileupload').fileupload({ progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress .bar').css( 'width', progress + '%' ); } });
3.2 需要一個(gè)div容器用來顯示進(jìn):
?
123
div id="progress" div class="bar" style="width: 0%;"/div /div
4. API
4.1 Initialization:
在上傳按鈕上調(diào)用fileupload()方法;
示例:
$('#fileupload').fileupload();
4.2 Options :
1: url:請(qǐng)求發(fā)送的目標(biāo)url
Type: string
Example: '/path/to/upload/handler.json'
2.Type: 文件上傳HTTP請(qǐng)求方式,可以選擇“POST”,“PUT”或者"PATCH",
默認(rèn)"POST"
Type: string
Example: 'PUT'
3. dataType:希望從服務(wù)器返回的數(shù)據(jù)類型,默認(rèn)"json"
Type: string
Example: 'json'
4. autoUpload:默認(rèn)情況下,只要用戶點(diǎn)擊了開始按鈕被添加至組件的文件會(huì)立即上傳。將autoUpload值設(shè)為true可以自動(dòng)上傳。
Type: boolean
Default: true
5. acceptFileTypes:允許上傳的的文件類型
Example: /(\.|\/)(gif|jpe?g|png|xlsx)$/i
6. maxFileSize: 最大上傳文件大小
Example: 999000 (999KB) //單位:B
7. minFileSize:最小上傳文件大小
Example: 100000 (100KB) //單位:B
8.previewMaxWidth : 圖片預(yù)覽區(qū)域最大寬度
Example: 100 //單位:px
4.3 Callback Options:
使用方法一:函數(shù)屬性
實(shí)例:
?
123456789101112
$('#fileupload').fileupload({drop: function (e, data) {$.each(data.files, function (index, file) {alert('Dropped file: ' + file.name);});},change: function (e, data) {$.each(data.files, function (index, file) {alert('Selected file: ' + file.name);});}});
使用方法二:綁定事件監(jiān)聽函數(shù)
實(shí)例:
?
123
$('#fileupload').bind('fileuploaddrop', function (e, data) {/* ... */}).bind('fileuploadchange', function (e, data) {/* ... */});
每個(gè)事件名稱都添加前綴:”fileupload”;
注意推薦使用第二種方法。
常用的回調(diào)函數(shù):
1. add: 當(dāng)文件被添加到上傳組件時(shí)被觸發(fā)
?
1
$('#fileupload').bind('fileuploadadd', function (e, data) {/* ... */});
或者$('#fileupload').on('fileuploadadd', function (e, data) {/* ... */});
2. processalways: 當(dāng)一個(gè)單獨(dú)的文件處理隊(duì)列結(jié)束(完成或失敗時(shí))觸發(fā)
3. progressall: 全局上傳處理事件的回調(diào)函數(shù)
Example:
?
1234567
$('#fileupload').on('fileuploadprogressall', function (e, data) { //進(jìn)度條顯示var progress = parseInt(data.loaded / data.total * 100, 10);$('#progress .progress-bar').css('width',progress + '%');});
4. fail : 上傳請(qǐng)求失敗時(shí)觸發(fā)的回調(diào)函數(shù),如果服務(wù)器返回一個(gè)帶有error屬性的json響應(yīng)這個(gè)函數(shù)將不會(huì)被觸發(fā)。
5. done : 上傳請(qǐng)求成功時(shí)觸發(fā)的回調(diào)函數(shù),如果服務(wù)器返回一個(gè)帶有error屬性的json響應(yīng)這個(gè)函數(shù)也會(huì)被觸發(fā)。
6. always : 上傳請(qǐng)求結(jié)束時(shí)(成功,錯(cuò)誤或者中止)都會(huì)被觸發(fā)。