资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

jquery上传文件,jquery上传文件进度条

用jquery如何实现提交表单点击提交之后显示正在上传中,之后显示上传成功的效果?

需要准备的材料分别有:电脑、html编辑器、浏览器。

创新互联是网站建设技术企业,为成都企业提供专业的成都网站设计、网站建设,网站设计,网站制作,网站改版等技术服务。拥有十年丰富建站经验和众多成功案例,为您定制适合企业的网站。十年品质,值得信赖!

1、首先,打开html编辑器,新建html文件,例如:index.html,并引入jquery。

2、在index.html中的script标签,输入jquery代码:

$('button').click(function () {

$('body').append('span正在上传中/span');

setTimeout("$('span').text('上传成功');", 1000);

});

3、浏览器运行index.html页面,点击提交按钮,显示了“正在上传中”。

4、例如过了1秒后变成了上传成功的提示。

jQuery实现文件上传。

/* 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;  

}  

}

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函数如下:

script src="js/jquery-1.3.2.min.js" type="text/javascript"/script  

script src="js/jquery.uploadify.v2.1.0.js" type="text/javascript"/script  

script src="js/jquery.uploadify.v2.1.0.min.js" type="text/javascript"/script  

script src="js/swfobject.js" type="text/javascript"/script  

link href="css/uploadify.css" rel="stylesheet" type="text/css" /  

/script

js函数:

script type="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 + "\r\n" +  

//  "文件名:" + fileObj.name + "\r\n" +  

//  "文件大小:" + fileObj.size + "\r\n" +  

//  "创建时间:" + fileObj.creationDate + "\r\n" +  

//  "最后修改时间:" + fileObj.modificationDate + "\r\n" +  

//  "文件类型:" + fileObj.type);  

//    }  

'onQueueComplete': function (queueData) {  

alert("文件上传成功!");                    

return;  

}  

});  

});

页面中的控件代码:

body  

form id="form1" runat="server"  

div id="fileQueue"         

/div  

div  

p  

input type="file" name="uploadify" id="uploadify"/  

input id="Button1" type="button" value="上传" onclick="javascript: $('#uploadify').uploadifyUpload()" /  

input id="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);  

}  

});  

});

后台一般处理文件:

using System;  

using System.Collections.Generic;  

using System.Linq;  

using System.IO;  

using System.Net;  

using System.Web;  

using System.Web.Services;  

namespace fupload  

{  

/// summary  

/// Handler1 的摘要说明  

/// /summary  

public class Handler1 : IHttpHandler  

{  

public void ProcessRequest(HttpContext context)  

{  

context.Response.ContentType = "text/plain";  

HttpPostedFile file = context.Request.Files["Filedata"];//对客户端文件的访问  

string uploadPath = 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");  

}  

}  

public bool IsReusable  

{  

get  

{  

return false;  

}  

}  

}  

}

以上方式基本可以实现多文件的上传,大文件大小是在控制在10M以下/。

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

更多用法可以 参考官网

jQuery fileupload 多文件上传

//js

$(function () {

//文件上传地址

//var url = '';

var url = '';

//初始化,主要是设置上传参数,以及事件处理方法(回调函数)

$('#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) {//设置上传进度事件的回调函数

var progress = parseInt(data.loaded / data.total * 5, 10);

$('#progress .bar').css(

'width',

progress + '%'

);

}

});

}); 

//上传至服务后,服务器返回json数据--上传图片的地址。

//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字节  

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

}  

}  

}

jquery file upload怎么使用

使用方法:

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上传文件进度条
当前地址:http://cdkjz.cn/article/dsgshcj.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220