RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
jquery批量上传,js批量上传文件

jquery批量上传图片插件uploadify 的例子 可以用的

!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "" 

成都创新互联公司主营唐山网站建设的网络公司,主营网站建设方案,重庆APP开发,唐山h5小程序设计搭建,唐山网站营销推广欢迎唐山等地区企业咨询

html xmlns="" 

meta http-equiv='Content-Type' content='text/html; charset=utf-8' /

titleFile upload /title 

link rel="Stylesheet" href="js/Plug-in/jquery.uploadify/uploadify.css" / 

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

script type="text/javascript" src="js/Plug-in/jquery.uploadify/swfobject.js"/script 

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

script type="text/javascript" 

$(document).ready(function() { 

$("#uploadify").uploadify({ 

'uploader': 'js/Plug-in/jquery.uploadify/uploadify.swf', 

'script': 'uploadify.php', 

'cancelImg': 'js/Plug-in/jquery.uploadify/cancel.png', 

'folder': 'uploadfile', 

'queueID': 'fileQueue', 

'auto': false, 

'multi': true, 

}); 

}); 

/script 

/head 

body 

MAX: 20M

/BR

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

a href="javascript:$('#uploadify').uploadifyUpload()"Upload/a| a href="javascript:$('#uploadify').uploadifyClearQueue()"cancel/a 

div id="fileQueue"/div 

/body 

/html

后台 uploadify.php

?php

/*

Uploadify v2.1.0

Release Date: August 24, 2009

Copyright (c) 2009 Ronnie Garcia, Travis Nickels

Permission is hereby granted, free of charge, to any person obtaining a copy

of this software and associated documentation files (the "Software"), to deal

in the Software without restriction, including without limitation the rights

to use, copy, modify, merge, publish, distribute, sublicense, and/or sell

copies of the Software, and to permit persons to whom the Software is

furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in

all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR

IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE

AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER

LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,

OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN

THE SOFTWARE.

*/

if (!empty($_FILES)) {

$tempFile = $_FILES['Filedata']['tmp_name'];

$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';

$targetFile =  str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];

$targetFile =  iconv("utf-8","gbk",$targetFile);

move_uploaded_file($tempFile,$targetFile);

echo "1";

}

?

我需要一个js或者jquery能批量上传图片+预览的功能。急~~~急~~~急~~

Web Uploader 项目,符合你的要求。

1、引入资源

使用Web Uploader文件上传需要引入三种资源:JS, CSS, SWF。

!--引入CSS--

link rel="stylesheet" type="text/css" href="webuploader文件夹/webuploader.css"

!--引入JS--

script type="text/javascript" src="webuploader文件夹/webuploader.js"/script

!--SWF在初始化的时候指定,在后面将展示--

2、Html

首先需要准备一个按钮,和一个用来存放添加的文件信息列表的容器。

!--dom结构部分--

div id="uploader-demo"

!--用来存放item--

div id="fileList" class="uploader-list"/div

div id="filePicker"选择图片/div

/div

3、Javascript

创建Web Uploader实例

// 初始化Web Uploader

var uploader = WebUploader.create({

// 选完文件后,是否自动上传。

auto: true,

// swf文件路径

swf: BASE_URL + '/js/Uploader.swf',

// 文件接收服务端。

server: '',

// 选择文件的按钮。可选。

// 内部根据当前运行是创建,可能是input元素,也可能是flash.

pick: '#filePicker',

// 只允许选择图片文件。

accept: {

title: 'Images',

extensions: 'gif,jpg,jpeg,bmp,png',

mimeTypes: 'image/*'

}

});

监听fileQueued事件,通过uploader.makeThumb来创建图片预览图。

PS: 这里得到的是Data URL数据,IE6、IE7不支持直接预览。可以借助FLASH或者服务端来完成预览。

// 当有文件添加进来的时候

uploader.on( 'fileQueued', function( file ) {

var $li = $(

'div id="' + file.id + '" class="file-item thumbnail"' +

'img' +

'div class="info"' + file.name + '/div' +

'/div'

),

$img = $li.find('img');

// $list为容器jQuery实例

$list.append( $li );

// 创建缩略图

// 如果为非图片文件,可以不用调用此方法。

// thumbnailWidth x thumbnailHeight 为 100 x 100

uploader.makeThumb( file, function( error, src ) {

if ( error ) {

$img.replaceWith('span不能预览/span');

return;

}

$img.attr( 'src', src );

}, thumbnailWidth, thumbnailHeight );

});

然后剩下的就是上传状态提示了,当文件上传过程中, 上传成功,上传失败,上传完成都分别对应uploadProgress, uploadSuccess, uploadError, uploadComplete事件。

// 文件上传过程中创建进度条实时显示。

uploader.on( 'uploadProgress', function( file, percentage ) {

var $li = $( '#'+file.id ),

$percent = $li.find('.progress span');

// 避免重复创建

if ( !$percent.length ) {

$percent = $('p class="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 = $('div class="error"/div').appendTo( $li );

}

$error.text('上传失败');

});

// 完成上传完了,成功或者失败,先删除进度条。

uploader.on( 'uploadComplete', function( file ) {

$( '#'+file.id ).find('.progress').remove();

});

更多细节,请查看js源码。

jquery 上传文件插件uploadify jsp版本

1、下载最新的zip压缩包

2、从其中提取文件。

下载插件安装包后,可以看到官方给出的例子。里面文件夹的几个主要文件:jquery.uploadify.js(完成上传功能的脚本文件,在调用页面引

用)、uploadify.css(外观样式表)、uploader.swf(上传控件的主体文件,flash控件)、upload.php(服务器端处

理文件,官方仅提供了php版的)。

下面我使用的是在MyEclipse部署的java版。注意:需要加入三个commons.jar包:io、logging、fileupload。

3、导入default.css,uploadify.css,jQuery脚本,swfobject脚本和Uploadify插件。并且添加调用插件使用$,在您的网页的head部分ready事件:

%@ page language="java" contentType="text/html; charset=utf-8"%

%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%

!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

html

head

base href="%=basePath%"

titleUpload/title

!--装载文件--

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

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

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

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

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

!--ready事件--

script type="text/javascript"

$(document).ready(function() {

$("#uploadify").uploadify({

'uploader'       : 'uploadify.swf',

'script'         : 'servlet/Upload',//后台处理的请求

'cancelImg'      : 'images/cancel.png',

'folder'         : 'uploads',//您想将文件保存到的路径

'queueID'        : 'fileQueue',//与下面的id对应

'queueSizeLimit'  :1,

'fileDesc'    : 'rar文件或zip文件’,    

'fileExt' : '*.rar;*.zip', //控制可上传文件的扩展名,启用本项时需同时声明fileDesc

'auto'           : false,

'multi'          : true,

'simUploadLimit' : 2,

'buttonText'     : 'BROWSE'

});

});

/script    /head

body

div id="fileQueue"/div

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

p

a href="javascript:jQuery('#uploadify').uploadifyUpload()"开始上传/anbsp;

a href="javascript:jQuery('#uploadify').uploadifyClearQueue()"取消所有上传/a

/p

/body

/html

4、后台处理的upload.java

package com.xzit.upload;

import java.io.File;

import java.io.IOException;

import java.util.Iterator;

import java.util.List;

import java.util.UUID;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

@SuppressWarnings("serial")

public class Upload extends HttpServlet {

@SuppressWarnings("unchecked")

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String savePath = this.getServletConfig().getServletContext()

.getRealPath("");

savePath = savePath + "/uploads/";

File f1 = new File(savePath);

System.out.println(savePath);

if (!f1.exists()) {

f1.mkdirs();

}

DiskFileItemFactory fac = new DiskFileItemFactory();

ServletFileUpload upload = new ServletFileUpload(fac);

upload.setHeaderEncoding("utf-8");

List fileList = null;

try {

fileList = upload.parseRequest(request);

} catch (FileUploadException ex) {

return;

}

IteratorFileItem it = fileList.iterator();

String name = "";

String extName = "";

while (it.hasNext()) {

FileItem item = it.next();

if (!item.isFormField()) {

name = item.getName();

long size = item.getSize();

String type = item.getContentType();

System.out.println(size + " " + type);

if (name == null || name.trim().equals("")) {

continue;

}

//扩展名格式: 

if (name.lastIndexOf(".") = 0) {

extName = name.substring(name.lastIndexOf("."));

}

File file = null;

do {

//生成文件名:

name = UUID.randomUUID().toString();

file = new File(savePath + name + extName);

} while (file.exists());

File saveFile = new File(savePath + name + extName);

try {

item.write(saveFile);

} catch (Exception e) {

e.printStackTrace();

}

}

}

response.getWriter().print(name + extName);

}

}

5、配置处理的servlet

Web.xml文件

?xml version="1.0" encoding="UTF-8"?

web-app version="2.4"

xmlns=""

xmlns:xsi=""

xsi:schemaLocation="

servlet

servlet-nameupload/servlet-name

servlet-classcom.xzit.upload.Upload/servlet-class

/servlet

servlet-mapping

servlet-nameupload/servlet-name

url-pattern/servlet/Upload/url-pattern

/servlet-mapping

welcome-file-list

welcome-fileindex.jsp/welcome-file

/welcome-file-list

/web-app

6.完成。

jqueryuploadify上传超过300张图片时出错

错误表现为部分文件没有加载到队列里, 实际为数据太多,问题可能

1 浏览器本身的限制

2 缓存的限制

3 其他限制

建议以合适的数量分批次上传

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 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批量上传,js批量上传文件
文章地址:http://scyingshan.cn/article/hodihe.html