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

jquery上傳文件demo

發布時間: 2023-07-03 19:40:49

1. 我需要一個js或者jquery能批量上傳圖片+預覽的功能。急~~~急~~~急~~

WebUploader項目,符合你的要求。

//文件上傳過程中創建進度條實時顯示。
uploader.on('uploadProgress',function(file,percentage){
var$li=$('#'+file.id),
$percent=$li.find('.progressspan');

//避免重復創建
if(!$percent.length){
$percent=$('<pclass="progress"><span></span></p>')
.appendTo($li)
.find('span');
}

$percent.css('width',percentage*100+'%');
});
//文件上傳成功,給item添加成功class,用樣式標記上傳成功。
uploader.on('uploadSuccess',function(file){
$('#'+file.id).addClass('upload-state-done');
});

//文件上傳失敗,顯示上傳出錯。
uploader.on('uploadError',function(file){
var$li=$('#'+file.id),
$error=$li.find('div.error');

//避免重復創建
if(!$error.length){
$error=$('<divclass="error"></div>').appendTo($li);
}

$error.text('上傳失敗');
});

//完成上傳完了,成功或者失敗,先刪除進度條。
uploader.on('uploadComplete',function(file){
$('#'+file.id).find('.progress').remove();
});

更多細節,請查看js源碼

2. 使用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)]

更多用法可以 參考官網

3. jquery的post方法上傳文件問題。

用jQuery 的Ajax文件上傳的組件:ajaxfileupload.js

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="ajaxfileupload.js"></script>
<script type="text/javascript">
function ajaxFileUpload()
{
$.ajaxFileUpload
(
{
url:'doajaxfileupload.php', //你處理上傳文件的服務端
secureuri:false,
fileElementId:'img',
dataType: 'json',
success: function (data)
{
alert(data.file_infor);
}
}
)

return false;
}
</script>

<input id="img" type="file" size="45" name="img" class="input">
<button class="button" id="buttonUpload" onclick="return ajaxFileUpload();">Upload</button>

4. 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.'"}';
}
}

}

5. jquery Uploadify上傳文件

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

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

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

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

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

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

6. 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;
}

}

7. jquery 多個 上傳文件教程

jquery 實現多個上傳文件教程:

首先創建解決方案,添加jquery的js和一些資源文件(如圖片和進度條顯示等):

jquery-1.3.2.min.js
jquery.uploadify.v2.1.0.js
jquery.uploadify.v2.1.0.min.js
swfobject.js
uploadify.css

1、頁面的基本代碼如下

這里用的是aspx頁面(html也是也可的)

頁面中引入的js和js函數如下:

<scriptsrc="js/jquery-1.3.2.min.js"type="text/javascript"></script>
<scriptsrc="js/jquery.uploadify.v2.1.0.js"type="text/javascript"></script>
<scriptsrc="js/jquery.uploadify.v2.1.0.min.js"type="text/javascript"></script>
<scriptsrc="js/swfobject.js"type="text/javascript"></script>
<linkhref="css/uploadify.css"rel="stylesheet"type="text/css"/>

</script>

js函數:

<scripttype="text/javascript">
$(document).ready(function(){

$("#uploadify").uploadify({
'uploader':'image/uploadify.swf',//uploadify.swf文件的相對路徑,該swf文件是一個帶有文字BROWSE的按鈕,點擊後淡出打開文件對話框
'script':'Handler1.ashx',//script:後台處理程序的相對路徑
'cancelImg':'image/cancel.png',
'buttenText':'請選擇文件',//瀏覽按鈕的文本,默認值:BROWSE。
'sizeLimit':999999999,//文件大小顯示
'floder':'Uploader',//上傳文件存放的目錄
'queueID':'fileQueue',//文件隊列的ID,該ID與存放文件隊列的div的ID一致
'queueSizeLimit':120,//上傳文件個數限制
'progressData':'speed',//上傳速度顯示
'auto':false,//是否自動上傳
'multi':true,//是否多文件上傳
//'onSelect':function(e,queueId,fileObj){
//alert("唯一標識:"+queueId+" "+
//"文件名:"+fileObj.name+" "+
//"文件大小:"+fileObj.size+" "+
//"創建時間:"+fileObj.creationDate+" "+
//"最後修改時間:"+fileObj.modificationDate+" "+
//"文件類型:"+fileObj.type);

//}
'onQueueComplete':function(queueData){
alert("文件上傳成功!");
return;
}

});
});

頁面中的控制項代碼:

<body>
<formid="form1"runat="server">
<divid="fileQueue">
</div>
<div>
<p>
<inputtype="file"name="uploadify"id="uploadify"/>
<inputid="Button1"type="button"value="上傳"onclick="javascript:$('#uploadify').uploadifyUpload()"/>
<inputid="Button2"type="button"value="取消"onclick="javascript:$('#uploadify').uploadifyClearQueue()"/>
</p>
</div>
</form>
</body>

函數主要參數:

$(document).ready(function(){
$('#fileInput1').fileUpload({
'uploader':'uploader.swf',//不多講了
'script':'/AjaxByJQuery/file.do',//處理Action
'cancelImg':'cancel.png',
'folder':'',//服務端默認保存路徑
'scriptData':{'methed':'uploadFile','arg1','value1'},
//向後台傳遞參數,methed,arg1為參數名,uploadFile,value1為對應的參數值,服務端通過request["arg1"]
'buttonText':'UpLoadFile',//按鈕顯示文字,不支持中文,解決方案見下
//'buttonImg':'圖片路徑',//通過設置背景圖片解決中文問題,就是把背景圖做成按鈕的樣子
'multi':'true',//多文件上傳開關
'fileExt':'*.xls;*.csv',//文件過濾器
'fileDesc':'.xls',//文件過濾器詳解見文檔
'onComplete':function(event,queueID,file,serverData,data){
//serverData為伺服器端返回的字元串值
alert(serverData);
}
});
});

後台一般處理文件:

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.IO;
usingSystem.Net;
usingSystem.Web;
usingSystem.Web.Services;
namespacefupload
{
///<summary>
///Handler1的摘要說明
///</summary>
publicclassHandler1:IHttpHandler
{

publicvoidProcessRequest(HttpContextcontext)
{
context.Response.ContentType="text/plain";

HttpPostedFilefile=context.Request.Files["Filedata"];//對客戶端文件的訪問

stringuploadPath=HttpContext.Current.Server.MapPath(@context.Request["folder"])+"\";//伺服器端文件保存路徑

if(file!=null)
{
if(!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);//創建服務端文件夾
}

file.SaveAs(uploadPath+file.FileName);//保存文件
context.Response.Write("上傳成功");
}

else
{
context.Response.Write("0");
}

}

publicboolIsReusable
{
get
{
returnfalse;
}
}
}
}

以上方式基本可以實現多文件的上傳,大文件大小是在控制在10M以下/。

8. jquery 用a標簽控制文件上傳

<htmlxmlns="http://www.w3.org/1999/xhtml">

<head>
<title>ajaxFileUpload文件上傳例子</title>
<scripttype="text/javascript"src="<%=baseURL%>/kinth/js/ajaxfileupload.js"></script>
<scripttype="text/javascript">
varflag=0;//flag作用:分兩種情況提交信息,如果是修改操作,沒有修改上傳文件,只修改其他欄位的信息時點保存也能提交信息
functionuploadFile(){
$.ajaxFileUpload({
url:baseURL+"/fileCatalog.do?method=save",//需要鏈接到伺服器地址
secureuri:true,
fileElementId:'file',//文件選擇框的id屬性
success:function(data,status){
varresults=$(data).find('body').html();
varobj=eval("("+results+")");
$("#fileSize").val(obj.fileSize);
$("#fileUrl").val(obj.fileUrl);
$('#fileCatalogForm').submit();
},error:function(data,status,e){
showDialogWithMsg('ideaMsg','提示','文件錯誤!');
}
});
}

functiongetFileName(obj)
{
flag=1;
varpos=-1;
if(obj.value.indexOf("/")>-1){
pos=obj.value.lastIndexOf("/")*1;
}elseif(obj.value.indexOf("\")>-1){
pos=obj.value.lastIndexOf("\")*1;
}
varfileName=obj.value.substring(pos+1);
$("#fileName").val(fileName);
$('.files').text(fileName);
}

functionev_save(){
if(submitMyForm('fileCatalogForm')){
if(flag==0){
$('#fileCatalogForm').submit();
}else{
uploadFile();
}
}
}

functionev_back(){
window.location.href=baseURL+'/fileCatalog.do?method=list';
}
</script>
</head>
<body>
<html:formstyleId="fileCatalogForm"action="/fileCatalog.do?method=save&fileFlag=true"method="post"enctype="application/x-www-form-urlencoded"style="text-align:left;">
<table>
<tr>
<td>附件上傳:</td>
<tdstyle="text-align:left;"id="fileTd">
<inputtype="file"name="file"id="file"onChange="getFileName(this);"/><br/>
</td>
<tdcolspan="2"class="tdr">
<olclass=files>
<c:iftest="${entity.resourceId!=null&&entity.resourceId!=''}"><li>${entity.fileName}&nbsp;&nbsp;上傳成功</li></c:if>
</ol>
</td>
</tr>
<c:iftest="${entity.resourceId==null||entity.resourceId==''}">
<inputtype="text"name="fileSize"id="fileSize">
</c:if>
<inputtype="hidden"id="fileUrl"name="fileUrl"value="${entity.fileUrl}"
</table>
</html:form>
</body>

熱點內容
android相機圖片 發布:2025-02-05 03:54:09 瀏覽:842
php小票列印機 發布:2025-02-05 03:42:00 瀏覽:613
vivo安卓手機如何連接藍牙耳機 發布:2025-02-05 03:40:30 瀏覽:957
youtubeapp緩存 發布:2025-02-05 03:33:10 瀏覽:747
vc遍歷文件夾 發布:2025-02-05 03:33:09 瀏覽:479
怎麼設dns伺服器地址 發布:2025-02-05 03:31:57 瀏覽:758
訪問伺服器文件夾 發布:2025-02-05 03:29:38 瀏覽:38
新手機的密碼在哪裡 發布:2025-02-05 03:28:04 瀏覽:480
lol按鍵源碼 發布:2025-02-05 03:11:47 瀏覽:899
wordpress安裝linux 發布:2025-02-05 03:01:53 瀏覽:140