當前位置:首頁 » 文件管理 » jquery插件文件上傳

jquery插件文件上傳

發布時間: 2022-11-26 16:42:04

『壹』 jquery Uploadify上傳文件

Uploadify是JQuery的一個上傳插件,實現的效果非常不錯,帶進度顯示。不過官方提供的實例時php版本的,本文將詳細介紹Uploadify在Aspnet中的使用,您也可以點擊下面的鏈接進行演示或下載。

首先按下面的步驟來實現一個簡單的上傳功能。

1 創建Web項目,命名為JQueryUploadDemo,從官網上下載最新的版本解壓後添加到項目中。

2 在項目中添加UploadHandler.ashx文件用來處理文件的上傳。

3 在項目中添加UploadFile文件夾,用來存放上傳的文件。

進行完上面三步後項目的基本結構如下圖:

『貳』 jquery上傳文件是怎麼實現的

本篇文章是對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>
<td><input 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); // 執行上傳操作

『叄』 jquery 上傳文件插件uploadify jsp版本

寫一個servlet,看這里
http://www.javaeye.com/topic/376101

『肆』 DWZ中怎樣整合JQuery的ajaxFileUpload上傳插件

jQuery插件AjaxFileUpload可以實現ajax文件上傳,需要jQuery庫文件和ajaxfileupload.js
一.引入部分
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="ajaxfileupload.js"></script>

二.<body>部分

<img src="images/nophoto.jpg" id="picture" width="160px" height="200px"/>
<input type="file" id="touxiang" name="photo" size="10" onchange="changImg()"/>

注意:使用AjaxFileUpload插件上傳文件可不需要form

<form name="form" action="" method="POST" enctype="multipart/form-data">

……相關html代碼……

</form>

三.js部分

function changImg(){

$.ajaxFileUpload
(
{
url:'XXX.action', //上傳文件的服務端
secureuri:false, //是否啟用安全提交
dataType: 'text', //數據類型
fileElementId:'touxiang', //表示文件域ID

//提交成功後處理函數 html為返回值,status為執行的狀態
success: function(html,status)
{

},

//提交失敗處理函數
error: function (html,status,e)
{

}
}
)

}

四.原理

利用jQuery的選擇器獲得file文件上傳框中的文件路徑值,然後動態的創建一個iframe,並在裡面建立一個新的file 文件框,提供post方式提交到後台。最後,返回結果到前台。

五.總結

使用jQuery插件AjaxFileUpload實現無刷新上傳文件非常實用,由於其簡單易用,因些這個插件相比其它文件上傳插件使用人數最多,非常值得推薦。

『伍』 jQuery fileupload 多文件上傳

//js
$(function(){
//文件上傳地址
//varurl='http://localhost/index.php/upload/do_upload';
varurl='http://localhost/index.php/uploadwe';
//初始化,主要是設置上傳參數,以及事件處理方法(回調函數)
$('#fileupload').fileupload({
autoUpload:true,//是否自動上傳
//url:url,//上傳地址
dataType:'json',
done:function(e,data){//設置文件上傳完畢事件的回調函數
//$.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){//設置上傳進度事件的回調函數
varprogress=parseInt(data.loaded/data.total*5,10);
$('#progress.bar').css(
'width',
progress+'%'
);
}
});
});
//上傳至服務後,伺服器返回json數據--上傳圖片的地址。
//html
<labelfor="text">上傳圖片</label>
<inputid="fileupload"type="file"name="files"data-url="<spanstyle="color:#ff6666;">jquery_save_img</span>"multiple>
//data-url為上傳至伺服器端的處理介面/地址,可替換js中的url
//伺服器端
functionjquery_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"<fontcolor='#FF0000'>文件不存在!</font>";
exit;
}

if($file['size']>$max_size){//判斷文件大小是否大於500000位元組
echo"<fontcolor='#FF0000'>上傳文件太大!</font>";
exit;
}
if(!in_array($file['type'],$arrType)){//判斷圖片文件的格式
echo"<fontcolor='#FF0000'>上傳文件格式不對!</font>xxx:".$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"<fontcolor='#FF0000'>同文件名已存在!</font>";
//exit;
}
if(!move_uploaded_file($file['tmp_name'],$picName)){
echo"<fontcolor='#FF0000'>移動文件出錯!</font>";
exit;
}
else{
/*
echo"<fontcolor='#FF0000'>圖片文件上傳成功!</font><br/>";
echo"<fontcolor='#0000FF'>圖片大小:$img</font><br/>";
echo"圖片預覽:<br><divstyle='border:#F001pxsolid;width:200px;height:200px'>
<imgsrc="".$picName.""width=200pxheight=200px>".$fname."</div>";
*/
echo'{"imgurl":"http://localhost/uploads/cloudy'.$fname.'"}';
}
}

}

『陸』 jQuery實現文件上傳。

/*jQuery實現文件上傳,參考例子如下:
packagecom.kinth.hddpt.file.action;

importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.util.ArrayList;
importjava.util.Calendar;
importjava.util.Enumeration;
importjava.util.Hashtable;
importjava.util.List;

importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;

importnet.sf.json.JSONArray;

importorg.apache.commons.logging.Log;
importorg.apache.commons.logging.LogFactory;
importorg.apache.struts.action.ActionForm;
importorg.apache.struts.action.ActionForward;
importorg.apache.struts.action.ActionMapping;
importorg.apache.struts.upload.FormFile;
importorg.hibernate.criterion.MatchMode;
importorg.hibernate.criterion.Order;
importorg.hibernate.criterion.Restrictions;

importcom.gdcn.bpaf.common.base.search.MyCriteria;
importcom.gdcn.bpaf.common.base.search.MyCriteriaFactory;
importcom.gdcn.bpaf.common.base.service.BaseService;
importcom.gdcn.bpaf.common.helper.PagerList;
importcom.gdcn.bpaf.common.helper.WebHelper;
importcom.gdcn.bpaf.common.taglib.SplitPage;
importcom.gdcn.bpaf.security.model.LogonVO;
importcom.gdcn.components.appauth.common.helper.DictionaryHelper;
importcom.kinth.common.base.action.BaseAction;
importcom.kinth.hddpt.file.action.form.FileCatalogForm;
importcom.kinth.hddpt.file.model.FileCatalog;
importcom.kinth.hddpt.file.service.FileCatalogService;
importcom.kinth.hddpt.file.util.MyZTreeNode;

/**
*<p>
*description:「文件上傳的Struts層請求處理類」
*</p>
*@date:2013-1-14
*/
<FileCatalog>{
@SuppressWarnings("unused")
privatestaticLoglog=LogFactory.getLog(FileCatalogAction.class);//日誌記錄
;

//刪除記錄的同時刪除相應文件
publicActionForwardfileDelete(ActionMappingmapping,ActionFormform,
HttpServletRequestrequest,HttpServletResponseresponse)
throwsException{
String[]id=request.getParameterValues("resourceId");

if(id!=null&&id[0].contains(",")){
id=id[0].split(",");
}
String[]fileUrls=newString[id.length];
for(intj=0;j<id.length;j++){
fileUrls[j]=fileCatalogService.findObject(id[j]).getFileUrl();
if(!isEmpty(fileUrls[j])){
//如果該文件夾不存在則創建一個uptext文件夾
Filefileup=newFile(fileUrls[j]);
if(fileup.exists()||fileup!=null){
fileup.delete();
}
}

fileCatalogService.deleteObject(id[j]);
}
setAllActionInfos(request);
returnlist(mapping,form,request,response);
}


@Override
publicActionForwardsave(ActionMappingmapping,ActionFormform,
HttpServletRequestrequest,HttpServletResponseresponse)
throwsException{
Stringid=request.getParameter("resourceId");
BooleanfileFlag=Boolean.valueOf(request.getParameter("fileFlag"));

if(fileFlag!=null&&fileFlag==true){
returnsuper.save(mapping,form,request,response);
}else{
StringfileUrl=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();
}
returnnull;
}

@SuppressWarnings("unchecked")
publicStringfileUpload(ActionFormform,HttpServletRequestrequest,Stringid,BooleanfileFlag)throwsFileNotFoundException,IOException{

request.setCharacterEncoding("GBK");

StringbasePath=getServlet().getServletConfig().getServletContext().getRealPath("")+"/";
StringfilePath="uploads/";//獲取項目根路徑;

/*注釋部分對應jqueryuploaploadify插件的後台代碼,只是還存在編碼問題,默認為utf-8
StringsavePath=getServlet().getServletConfig().getServletContext().getRealPath("");//獲取項目根路徑
savePath=savePath+"\uploads\";
//讀取上傳來的文件信息
Hashtable<String,FormFile>fileHashtable=form.getMultipartRequestHandler().getFileElements();
Enumeration<String>enumeration=fileHashtable.keys();
enumeration.hasMoreElements();
Stringkey=(String)enumeration.nextElement();

FormFileformFile=(FormFile)fileHashtable.get(key);

Stringfilename=formFile.getFileName().trim();//文件名
filename=newEncodeChange().changeCode(filename);
Stringfiletype=filename.substring(filename.lastIndexOf(".")+1);//文件類型
savePath=savePath+filetype+"\";
System.out.println("path:"+savePath);
StringrealPath=savePath+filename;//真實文件路徑

//如果該文件夾不存在則創建一個文件夾
Filefileup=newFile(savePath);
if(!fileup.exists()||fileup==null){
fileup.mkdirs();
}
if(!filename.equals("")){
//在這里上傳文件
InputStreamis=formFile.getInputStream();
OutputStreamos=newFileOutputStream(realPath);
intbytesRead=0;
byte[]buffer=newbyte[8192];
while((bytesRead=is.read(buffer,0,8192))!=-1){
os.write(buffer,0,bytesRead);
}
os.close();
is.close();
//如果是修改操作,則刪除原來的文件
Stringid=request.getParameter("resourceId");
if(!isEmpty(id)){
FileCatalogfileCatalog=fileCatalogService.findObject(id);
StringfileUrl=fileCatalog.getFileUrl();
if(!isEmpty(fileUrl)){
Filefiledel=newFile(fileUrl);
if(filedel.exists()||filedel!=null){
filedel.delete();
}
}

request.setAttribute("entity",fileCatalog);
}

response.getWriter().print(realPath);//向頁面端返回結果信息
}*/

//讀取上傳來的文件信息
Hashtable<String,FormFile>fileHashtable=form.getMultipartRequestHandler().getFileElements();
Enumeration<String>enumeration=fileHashtable.keys();
enumeration.hasMoreElements();
Stringkey=(String)enumeration.nextElement();

FormFileformFile=(FormFile)fileHashtable.get(key);

Stringfilename=formFile.getFileName().trim();//文件名
Stringfiletype=filename.substring(filename.lastIndexOf(".")+1);//文件類型
IntegerfileSize=formFile.getFileSize();


filePath+=Calendar.getInstance().get(Calendar.YEAR)+"/"+filetype+"/";
StringrealPath=basePath+filePath+filename;//真實文件路徑

if(!filename.equals("")){
//如果是修改操作,則刪除原來的文件
if(!isEmpty(id)){
FileCatalogfileCatalog=fileCatalogService.findObject(id);
StringfileUrl=fileCatalog.getFileUrl();
if(!isEmpty(fileUrl)){
fileUrl=basePath+fileUrl;
Filefiledel=newFile(fileUrl);
if(filedel.exists()||filedel!=null){
filedel.delete();
}
}
request.setAttribute("entity",fileCatalog);
}
//如果該文件夾不存在則創建一個文件夾
Filefileup=newFile(basePath+filePath);
if(!fileup.exists()||fileup==null){
fileup.mkdirs();
}
//在這里上傳文件
InputStreamis=formFile.getInputStream();
OutputStreamos=newFileOutputStream(realPath);
intbytesRead=0;
byte[]buffer=newbyte[8192];
while((bytesRead=is.read(buffer,0,8192))!=-1){
os.write(buffer,0,bytesRead);
}
os.close();
is.close();
}
filePath+=filename;
Stringresult="{"fileName":""+filename+"","fileType":""+filetype+"","fileSize":"+fileSize+","fileUrl":""+filePath+""}";
returnresult;

}

(){
returnfileCatalogService;
}

(){
this.fileCatalogService=fileCatalogService;
}

}

『柒』 如何用 jQuery 直接傳文件至七牛

操作方法如下: jquery有個插件叫uplodify,你搜下,可以用它來上傳,並有上傳進度條等功能!

『捌』 使用jquery.form.js實現文件上傳及進度條前端代碼

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)]

更多用法可以 參考官網

『玖』 jsp中使用jquery的ajaxfileupload插件怎麼實現非同步上傳

ajaxfileupload實現非同步上傳的完整例子:
JSP頁面中引入的script代碼:
<script>
function ajaxFileUpload()
{
$("#loading").ajaxStart(function(){
$(this).show();
})//開始上傳文件時顯示一個圖片
.ajaxComplete(function(){
$(this).hide();
});//文件上傳完成將圖片隱藏起來

$.ajaxFileUpload({
url:'AjaxImageUploadAction.action',//用於文件上傳的伺服器端請求地址
secureuri:false,//一般設置為false
fileElementId:'imgfile',//文件上傳空間的id屬性 <input type="file" id="imgfile" name="file" />
dataType: 'json',//返回值類型 一般設置為json
success: function (data, status) //伺服器成功響應處理函數
{
alert(data.message);//從伺服器返回的json中取出message中的數據,其中message為在struts2中定義的成員變數

if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else
{
alert(data.message);
}
}
},
error: function (data, status, e)//伺服器響應失敗處理函數
{
alert(e);
}
}
)

return false;
}
</script>
struts.xml配置文件中的配置方法:
<struts>
<package name="struts2" extends="json-default">
<action name="AjaxImageUploadAction" class="com.test.action.ImageUploadAction">
<result type="json" name="success">
<param name="contentType">text/html</param>
</result>
<result type="json" name="error">
<param name="contentType">text/html</param>
</result>
</action>
</package>
</struts>
上傳處理的Action ImageUploadAction.action
package com.test.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Arrays;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class ImageUploadAction extends ActionSupport {

private File imgfile;
private String imgfileFileName;
private String imgfileFileContentType;
private String message = "你已成功上傳文件";
public File getImgfile() {
return imgfile;
}
public void setImgfile(File imgfile) {
this.imgfile = imgfile;
}
public String getImgfileFileName() {
return imgfileFileName;
}
public void setImgfileFileName(String imgfileFileName) {
this.imgfileFileName = imgfileFileName;
}
public String getImgfileFileContentType() {
return imgfileFileContentType;
}
public void setImgfileFileContentType(String imgfileFileContentType) {
this.imgfileFileContentType = imgfileFileContentType;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}

@SuppressWarnings("deprecation")
public String execute() throws Exception {

String path = ServletActionContext.getRequest().getRealPath("/upload/mri_img_upload");
String[] imgTypes = new String[] { "gif", "jpg", "jpeg", "png","bmp" };
try {
File f = this.getImgfile();

String fileExt = this.getImgfileFileName().substring(this.getImgfileFileName().lastIndexOf(".") + 1).toLowerCase();
/*
if(this.getImgfileFileName().endsWith(".exe")){
message="上傳的文件格式不允許!!!";
return ERROR;
}*/
/**
* 檢測上傳文件的擴展名是否合法
* */
if (!Arrays.<String> asList(imgTypes).contains(fileExt)) {
message="只能上傳 gif,jpg,jpeg,png,bmp等格式的文件!";
return ERROR;
}

FileInputStream inputStream = new FileInputStream(f);
FileOutputStream outputStream = new FileOutputStream(path + "/"+ this.getImgfileFileName());
byte[] buf = new byte[1024];
int length = 0;
while ((length = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, length);
}
inputStream.close();
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
message = "文件上傳失敗了!!!!";
}
return SUCCESS;
}
}

『拾』 如何通過jQuery的上傳插件ajaxFileUpload上傳文件給webservice

var
elementIds=["flag"];
//flag為id、name屬性名
$.ajaxFileUpload({
url:
'uploadAjax.htm',
type:
'post',
secureuri:
false,
//一般設置為false
fileElementId:
'file',
//
上傳文件的id、name屬性名
dataType:
'text',
//返回值類型,一般設置為json、application/json
elementIds:
elementIds,
//傳遞參數到伺服器
success:
function(data,
status){
alert(data);
},
error:
function(data,
status,
e){
alert(e);
}
});

熱點內容
安卓如何遠程簽到 發布:2024-10-05 14:11:11 瀏覽:299
阿里雲伺服器控制面板 發布:2024-10-05 13:57:48 瀏覽:816
涉法涉訴信訪問題意見 發布:2024-10-05 13:56:23 瀏覽:893
華為路由器配置導出的方法有哪些 發布:2024-10-05 13:55:36 瀏覽:161
我的世界好玩伺服器拍視頻 發布:2024-10-05 13:23:19 瀏覽:553
穿越火線掛機腳本 發布:2024-10-05 13:05:44 瀏覽:33
分解質因數c語言 發布:2024-10-05 12:15:53 瀏覽:778
mysql存儲過程字元編碼 發布:2024-10-05 12:05:48 瀏覽:182
c語言命名 發布:2024-10-05 11:56:38 瀏覽:617
編程哪個好學習 發布:2024-10-05 11:50:59 瀏覽:1000