本篇文章是對Jquery中的LigerUI實現文件上傳的方法,進行了分析介紹,需要的朋友可以參考下
創新互聯公司是一家集網站建設,肅南裕固族自治企業網站建設,肅南裕固族自治品牌網站建設,網站定制,肅南裕固族自治網站建設報價,網絡營銷,網絡優化,肅南裕固族自治網站推廣為一體的創新建站企業,幫助傳統企業提升企業形象加強企業競爭力。可充分滿足這一群體相比中小企業更為豐富、高端、多元的互聯網需求。同時我們時刻保持專業、時尚、前沿,時刻以成就客戶成長自我,堅持不斷學習、思考、沉淀、凈化自己,讓我們為更多的企業打造出實用型網站。
一、在Head中加入
script src="../lib/js/ajaxfileupload.js" type="text/javascript"/script
script src="../lib/js/ligerui.expand.js" type="text/javascript"/script
二、Html中的Div代碼
復制代碼 代碼如下:
div id="AppendBill_Div" style="display:none;" %-- 上傳 - 單 --%
table style="height:100%;width:100%"
tr style="height:40px"
td style="width:20%"
圖標:
/td
tdinput type="file" style="width:200px" id="fileupload" name="fileupload"/
/td
/tr
/table
/div
三、Js中-寫的是關鍵部分,會LigerUI的朋友-你懂得
1、grid中添加項【存地址字段】
{ display: "掃描件", name: "AppendBillPath", width: 120, type: "text", align: "left" }
2、Form可添加項【存地址和彈出選擇框】
{ 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】--
復制代碼 代碼如下:
var AppendBillPathDetail = null;
function f_selectAppendBillPath_1() {
var imageurl = $("#AppendBill").val();
var AppendBill_Id = $("#AppendBill").val(); // 單號
if (imageurl.length == 0) {
LG.showError("您沒有輸入單號,請輸入隨單號!");
return;
}
if (AppendBillPathDetail) {
AppendBillPathDetail.show();
}
else {
AppendBillPathDetail = $.ligerDialog.open({
target: $("#AppendBill_Div"), title: '添加圖標',
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("請上傳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
四、后臺cs,寫一句關鍵的,可以返回參數,前臺提示
string url = Server.MapPath("/Image/" + gfilename + filenameext); // 執行上傳操作
ajax的表單提交只能提交data數據到后臺,沒法實現file文件的上傳還有展示進度功能,這里用到form.js的插件來實現,搭配css樣式簡單易上手,而且高大上,推薦使用。
需要解釋下我的結構, #upload-input-file 的input標簽是真實的文件上傳按鈕,包裹form標簽后可以實現上傳功能, #upload-input-btn 的button標簽是展示給用戶的按鈕,因為需要樣式的美化。上傳完成生成的文件名將會顯示在 .upload-file-result 里面, .progress 是進度條的位置,先讓他隱藏加上 hidden 的class, .progress-bar 是進度條的主體, .progress-bar-status 是進度條的文本提醒。
去掉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)]
更多用法可以 參考官網
/*?jQuery實現文件上傳,參考例子如下:
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層請求處理類”?
*?/p?
*?@date?:?2013-1-14?
*/??
public?class?FileCatalogAction?extends?BaseActionFileCatalog?{??
@SuppressWarnings("unused")??
private?static?Log?log?=?LogFactory.getLog(FileCatalogAction.class);?//?日志記錄??
private?FileCatalogService?fileCatalogService;??
//?刪除記錄的同時刪除相應文件??
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]))?{??
//?如果該文件夾不存在則創建一個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/";?//?獲取項目根路徑????;??
/*注釋部分對應jquery?upload?uploadify插件的后臺代碼,只是還存在編碼問題,默認為utf-8?
String?savePath?=?getServlet().getServletConfig().getServletContext().getRealPath("");?//?獲取項目根路徑?
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;?//真實文件路徑?
//如果該文件夾不存在則創建一個文件夾?
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);//?向頁面端返回結果信息?
}*/??
//?讀取上傳來的文件信息??
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;??//?真實文件路徑??
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);??
}??
//?如果該文件夾不存在則創建一個文件夾??
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 顯示上傳進度條:
?
123456789
$('#fileupload').fileupload({ progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress .bar').css( 'width', progress + '%' ); } });
3.2 需要一個div容器用來顯示進:
?
123
div id="progress" div class="bar" style="width: 0%;"/div /div
4. API
4.1 Initialization:
在上傳按鈕上調用fileupload()方法;
示例:
$('#fileupload').fileupload();
4.2 Options :
1: url:請求發送的目標url
Type: string
Example: '/path/to/upload/handler.json'
2.Type: 文件上傳HTTP請求方式,可以選擇“POST”,“PUT”或者"PATCH",
默認"POST"
Type: string
Example: 'PUT'
3. dataType:希望從服務器返回的數據類型,默認"json"
Type: string
Example: 'json'
4. autoUpload:默認情況下,只要用戶點擊了開始按鈕被添加至組件的文件會立即上傳。將autoUpload值設為true可以自動上傳。
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 : 圖片預覽區域最大寬度
Example: 100 //單位:px
4.3 Callback Options:
使用方法一:函數屬性
實例:
?
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);});}});
使用方法二:綁定事件監聽函數
實例:
?
123
$('#fileupload').bind('fileuploaddrop', function (e, data) {/* ... */}).bind('fileuploadchange', function (e, data) {/* ... */});
每個事件名稱都添加前綴:”fileupload”;
注意推薦使用第二種方法。
常用的回調函數:
1. add: 當文件被添加到上傳組件時被觸發
?
1
$('#fileupload').bind('fileuploadadd', function (e, data) {/* ... */});
或者$('#fileupload').on('fileuploadadd', function (e, data) {/* ... */});
2. processalways: 當一個單獨的文件處理隊列結束(完成或失敗時)觸發
3. progressall: 全局上傳處理事件的回調函數
Example:
?
1234567
$('#fileupload').on('fileuploadprogressall', function (e, data) { //進度條顯示var progress = parseInt(data.loaded / data.total * 100, 10);$('#progress .progress-bar').css('width',progress + '%');});
4. fail : 上傳請求失敗時觸發的回調函數,如果服務器返回一個帶有error屬性的json響應這個函數將不會被觸發。
5. done : 上傳請求成功時觸發的回調函數,如果服務器返回一個帶有error屬性的json響應這個函數也會被觸發。
6. always : 上傳請求結束時(成功,錯誤或者中止)都會被觸發。
文章名稱:jquery文件上傳,jquery文件上傳帶session
URL地址:http://vcdvsql.cn/article28/dsdiscp.html
成都網站建設公司_創新互聯,為您提供云服務器、電子商務、企業網站制作、網站收錄、用戶體驗、網站內鏈
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯