使用方法:

創(chuàng)新互聯(lián)公司堅持“要么做到,要么別承諾”的工作理念,服務領(lǐng)域包括:成都做網(wǎng)站、網(wǎng)站建設(shè)、外貿(mào)營銷網(wǎng)站建設(shè)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣等服務,滿足客戶于互聯(lián)網(wǎng)時代的泗縣網(wǎng)站設(shè)計、移動媒體設(shè)計的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
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:
在上傳按鈕上調(diào)用fileupload()方法;
示例:
$('#fileupload').fileupload();
4.2 Options :
1: url:請求發(fā)送的目標url
Type: string
Example: '/path/to/upload/handler.json'
2.Type: 文件上傳HTTP請求方式,可以選擇“POST”,“PUT”或者"PATCH",
默認"POST"
Type: string
Example: 'PUT'
3. dataType:希望從服務器返回的數(shù)據(jù)類型,默認"json"
Type: string
Example: 'json'
4. autoUpload:默認情況下,只要用戶點擊了開始按鈕被添加至組件的文件會立即上傳。將autoUpload值設(shè)為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 : 圖片預覽區(qū)域最大寬度
Example: 100 //單位:px
4.3 Callback Options:
使用方法一:函數(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ù)
實例:
?
123
$('#fileupload').bind('fileuploaddrop', function (e, data) {/* ... */}).bind('fileuploadchange', function (e, data) {/* ... */});
每個事件名稱都添加前綴:”fileupload”;
注意推薦使用第二種方法。
常用的回調(diào)函數(shù):
1. add: 當文件被添加到上傳組件時被觸發(fā)
?
1
$('#fileupload').bind('fileuploadadd', function (e, data) {/* ... */});
或者$('#fileupload').on('fileuploadadd', function (e, data) {/* ... */});
2. processalways: 當一個單獨的文件處理隊列結(jié)束(完成或失敗時)觸發(fā)
3. progressall: 全局上傳處理事件的回調(diào)函數(shù)
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 : 上傳請求失敗時觸發(fā)的回調(diào)函數(shù),如果服務器返回一個帶有error屬性的json響應這個函數(shù)將不會被觸發(fā)。
5. done : 上傳請求成功時觸發(fā)的回調(diào)函數(shù),如果服務器返回一個帶有error屬性的json響應這個函數(shù)也會被觸發(fā)。
6. always : 上傳請求結(jié)束時(成功,錯誤或者中止)都會被觸發(fā)。
本篇文章是對Jquery中的LigerUI實現(xiàn)文件上傳的方法,進行了分析介紹,需要的朋友可以參考下
一、在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中-寫的是關(guān)鍵部分,會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,寫一句關(guān)鍵的,可以返回參數(shù),前臺提示
string url = Server.MapPath("/Image/" + gfilename + filenameext); // 執(zhí)行上傳操作
/*?jQuery實現(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層請求處理類”?
*?/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]))?{??
//?如果該文件夾不存在則創(chuàng)建一個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;?//真實文件路徑?
//如果該文件夾不存在則創(chuàng)建一個文件夾?
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;??//?真實文件路徑??
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)建一個文件夾??
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;??
}??
}
//js
$(function?()?{
//文件上傳地址
//var?url?=?'';
var?url?=?'';
//初始化,主要是設(shè)置上傳參數(shù),以及事件處理方法(回調(diào)函數(shù))
$('#fileupload').fileupload({
autoUpload:?true,//是否自動上傳
//url:?url,//上傳地址
dataType:?'json',
done:?function?(e,?data)?{//設(shè)置文件上傳完畢事件的回調(diào)函數(shù)
//$.each(data.result.files,?function?(index,?file)?{
$("#myimg").attr({src:data.result.imgurl});
$("#myimg").css({width:"290px",height:"218px"});
//alert(data.result);
},
progressall:?function?(e,?data)?{//設(shè)置上傳進度事件的回調(diào)函數(shù)
var?progress?=?parseInt(data.loaded?/?data.total?*?5,?10);
$('#progress?.bar').css(
'width',
progress?+?'%'
);
}
});
});?
//上傳至服務后,服務器返回json數(shù)據(jù)--上傳圖片的地址。
//html
label?for="text"上傳圖片/label
input?id="fileupload"?type="file"?name="files"?data-url="span?style="color:#ff6666;"jquery_save_img/span"?multiple
//data-url為上傳至服務器端的處理接口/地址,可替換js中的url
//服務器端
function?jquery_save_img()??
{??
$arrType=array('image/jpg','image/gif','image/png','image/bmp','image/pjpeg','image/jpeg');??
$max_size='500000000000';??????//?最大文件限制(單位:byte)??
$upfile='./uploads';?//圖片目錄路徑??
$file=$_FILES['files'];??
/*?
echo?'filename:'.$file['tmp_name'].';br?/';?
echo?'size:'.$file['size'].';br?/';?
echo?'type:'.$file['type'].';br?/';?
echo?'name:'.$file['name'].';br?/';?
*/??
if($_SERVER['REQUEST_METHOD']=='POST'){?//判斷提交方式是否為POST??
if(!is_uploaded_file($file['tmp_name'])){?//判斷上傳文件是否存在??
echo?"font?color='#FF0000'文件不存在!/font";??
exit;??
}??
if($file['size']$max_size){??//判斷文件大小是否大于500000字節(jié)??
echo?"font?color='#FF0000'上傳文件太大!/font";??
exit;??
}???
if(!in_array($file['type'],$arrType)){??//判斷圖片文件的格式??
echo?"font?color='#FF0000'上傳文件格式不對!/fontxxx:".$file['type'];??
exit;??
}??
if(!file_exists($upfile)){??//?判斷存放文件目錄是否存在??
mkdir($upfile,0777,true);??
}???
$imageSize=getimagesize($file['tmp_name']);??
$img=$imageSize[0].'*'.$imageSize[1];??
$fname=$file['name'];??
$ftype=explode('.',$fname);??
$picName=$upfile."/cloudy".$fname;??
if(file_exists($picName)){??
//echo?"font?color='#FF0000'同文件名已存在!/font";??
//exit;??
}??
if(!move_uploaded_file($file['tmp_name'],$picName)){????
echo?"font?color='#FF0000'移動文件出錯!/font";??
exit;??
}??
else{??
/*?
echo?"font?color='#FF0000'圖片文件上傳成功!/fontbr/";?
echo?"font?color='#0000FF'圖片大小:$img/fontbr/";?
echo?"圖片預覽:brdiv?style='border:#F00?1px?solid;?width:200px;height:200px'?
img?src=\"".$picName."\"?width=200px?height=200px".$fname."/div";?
*/??
echo?'{"imgurl":"'.$fname.'"}';??
}??
}??
}
ajax的表單提交只能提交data數(shù)據(jù)到后臺,沒法實現(xiàn)file文件的上傳還有展示進度功能,這里用到form.js的插件來實現(xiàn),搭配css樣式簡單易上手,而且高大上,推薦使用。
需要解釋下我的結(jié)構(gòu), #upload-input-file 的input標簽是真實的文件上傳按鈕,包裹form標簽后可以實現(xiàn)上傳功能, #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)]
更多用法可以 參考官網(wǎng)
本文題目:jquery文件上傳,jQuery文件上傳取消事件
分享鏈接:http://chinadenli.net/article42/dsipghc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供軟件開發(fā)、虛擬主機、Google、網(wǎng)站制作、移動網(wǎng)站建設(shè)、營銷型網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)