WEB版一次选择多个文件进行批量上传(WebUploader)的解决方案
本人在2010年时使用swfupload为核心进行文件的批量上传的解决方案。见文章:WEB版一次选择多个文件进行批量上传(swfupload)的解决方案。
本人在2013年时使用plupload为核心进行文件的批量上传的解决方案。见文章:WEB版一次选择多个文件进行批量上传(Plupload)的解决方案
最近在学习百度的开源上传组件WebUploader,写了一些示例以记录。WebUploader的缺点是没有一个比较好的现成的界面,这个界面需要自己去实现。自由度高了一些。
WebUploader是由Baidu WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现代文件上传组件。在现代的浏览器里面能充分发挥HTML5的优势,同时又不摒弃主流IE浏览器,沿用原来的FLASH运行时,兼容IE6+,iOS 6+, android 4+。两套运行时,同样的调用方式,可供用户任意选用。
关于WebUploader的功能说明:
分片、并发
分片与并发结合,将一个大文件分割成多块,并发上传,极大地提高大文件的上传速度。
当网络问题导致传输错误时,只需要重传出错分片,而不是整个文件。另外分片传输能够更加实时的跟踪上传进度。
预览、压缩
支持常用图片格式jpg,jpeg,gif,bmp,png预览与压缩,节省网络数据传输。
解析jpeg中的meta信息,对于各种orientation做了正确的处理,同时压缩后上传保留图片的所有原始meta数据。
多途径添加文件
支持文件多选,类型过滤,拖拽(文件&文件夹),图片粘贴功能。
粘贴功能主要体现在当有图片数据在剪切板中时(截屏工具如QQ(Ctrl + ALT + A), 网页中右击图片点击复制),Ctrl + V便可添加此图片文件。
HTML5 & FLASH
兼容主流浏览器,接口一致,实现了两套运行时支持,用户无需关心内部用了什么内核。
同时Flash部分没有做任何UI相关的工作,方便不关心flash的用户扩展和自定义业务需求。
MD5秒传
当文件体积大、量比较多时,支持上传前做文件md5值验证,一致则可直接跳过。
如果服务端与前端统一修改算法,取段md5,可大大提升验证性能,耗时在20ms左右。
易扩展、可拆分
采用可拆分机制, 将各个功能独立成了小组件,可自由搭配。
采用AMD规范组织代码,清晰明了,方便高级玩家扩展。
一: 下面就是利用WebUploader组件,让客户一次选择多个文件,然后将选择的文件上传到服务器的批量文件解决方案。
让我们先来看看客户端的界面效果图。(多选文件,批量上传,上传进度显示)
1) 显示界面:
图1
2) 进行多文件选择:
图2
3) 上传进度显示
图3
图4
说明:见上图WebUploader默认是3个线程一起并发上传文件。如果需要增加并发数,或是减少并发数。可以修改threads属性,这个属性就是允许的最大上传并发数。
3) 上传成功显示
图5
二:具体的代码与操作步骤:
第一步,要完成下面的示例,必须先准备好WebUploader组件。
1) WebUploader:大家可以访问WebUploader官方网站:http://fex.baidu.com/webuploader/download.html,在这个网站上可以下载到组件与demo。
第二步,这个示例的目录结构如图:
1.主要目录结构
2. 此示例中用到的js脚本文件与css文件。
第三步,前台部分准备客户操作的WEB界面,如下[WebUploaderFileByBaidu2.aspx、UploaderFileByBaidu.ashx]
1) 前台客户端代码,其中WebUploaderFileByBaidu2.aspx的代码如下,WebUploaderFileByBaidu2.aspx.cs文件中只使用默认的代码,不用添加任何代码。
Html代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebUploaderFileByBaidu2.aspx.cs" Inherits="WebApplication1.WebUploaderFileByBaidu2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>WebUploader文件上传示例</title> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<link href="Scripts/webuploader/webuploader.css" rel="stylesheet" />
<script type="text/javascript" src="Scripts/webuploader/webuploader.min.js"></script> <link href="https://cdn.bootcss.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet"/>
<link href="Scripts/style.css" rel="stylesheet" />
<link href="Scripts/demo.css" rel="stylesheet" />
<link href="Scripts/font-awesome.css" rel="stylesheet" /> <script type="text/javascript">
var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../../";
// 文件上传
jQuery(function () {
var $ = jQuery,
$list = $('#fileList'),
$btn = $('#ctlBtn'),
state = 'pending',
uploader;
uploader = WebUploader.create({
// 不压缩image
resize: false, // swf文件路径
swf: applicationPath + 'Script/webuploader/Uploader.swf', // 文件接收服务端。
server: 'UploaderFileByBaidu.ashx', // 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#picker' }); // 当有文件添加进来的时候
uploader.on('fileQueued', function (file) { $list.append('<div id="' + file.id + '" class="item">' +
'<h4 class="info">' + file.name + '</h4>' +
'<p class="state">等待上传...</p>' +
'</div>'); }); // 文件上传过程中创建进度条实时显示。
uploader.on('uploadProgress', function (file, percentage) { var $li = $('#' + file.id),
$percent = $li.find('.progress .progress-bar');
// 避免重复创建
if (!$percent.length) {
$percent = $('<div class="progress progress-striped active">' +
'<div class="progress-bar" role="progressbar" style="width: 0%">' +
'</div>' +
'</div>').appendTo($li).find('.progress-bar');
}
$li.find('p.state').text('上传中');
$percent.css('width', percentage * 100 + '%'); }); uploader.on('uploadSuccess', function (file) {
$('#' + file.id).find('p.state').text('已上传');
}); uploader.on('uploadError', function (file) {
$('#' + file.id).find('p.state').text('上传出错');
}); uploader.on('uploadComplete', function (file) {
$('#' + file.id).find('.progress').fadeOut();
});
uploader.on('all', function (type) {
if (type === 'startUpload') {
state = 'uploading';
} else if (type === 'stopUpload') {
state = 'paused';
} else if (type === 'uploadFinished') {
state = 'done';
}
if (state === 'uploading') {
$btn.text('暂停上传');
} else {
$btn.text('开始上传');
} }); $btn.on('click', function () {
if (state === 'uploading') {
uploader.stop();
} else {
uploader.upload();
}
});
});
</script>
</head> <body> <div class="container-fluid">
<div class="col-md-10">
<div class="row">文件上传示例:</div>
<div class="row">
<div id="uploader" class="wu-example">
<!--用来存放文件信息-->
<div id="fileList" class="uploader-list"></div>
<div class="btns">
<div id="picker" class="btn btn-primary">选择文件</div> </div> </div>
</div> <div class="row"> </div>
<div class="row"> <button id="ctlBtn" class="btn btn-default">开始上传</button></div>
</div>
<div>
</div>
</div> </body>
</html>
以上代码最后的显示结果如下图:
图8.
2) 接收前端用户上传的文件,并把文件保存到指定目录中。UploaderFileByBaidu.ashx文件中使用默认的代码,不需要添加任何代码。UploaderFileByBaidu.ashx.cs文件的代码如下:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
namespace WebApplication1
{
/// <summary>
/// UploaderFileByBaidu 的摘要说明
/// </summary>
public class UploaderFileByBaidu : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
context.Response.ContentEncoding = Encoding.UTF8;
if (context.Request["REQUEST_METHOD"] == "OPTIONS")
{
context.Response.End();
} SaveFile();
} /// <summary>
/// 文件保存操作
/// </summary>
/// <param name="basePath"></param>
private void SaveFile(string basePath = "~/Upload/Images/")
{ basePath = FileHelper.GetUploadPath();
string Datedir = DateTime.Now.ToString("yy-MM-dd");
string updir = basePath + "\\" + Datedir;
string extname = string.Empty;
string fullname = string.Empty;
string filename = string.Empty; HttpFileCollection files = System.Web.HttpContext.Current.Request.Files; if (files.Count == )
{
var result = "{\"jsonrpc\" : \"2.0\", \"error\" : \"保存失败\",\"id\" : \"id\"}";
System.Web.HttpContext.Current.Response.Write(result);
}
if (!Directory.Exists(updir))
Directory.CreateDirectory(updir); var suffix = files[].ContentType.Split('/');
var _suffix = suffix[].Equals("jpeg", StringComparison.CurrentCultureIgnoreCase) ? "" : suffix[];
var _temp = System.Web.HttpContext.Current.Request["name"]; if (!string.IsNullOrEmpty(_temp))
{
filename = _temp;
}
else
{
Random rand = new Random( * (int)DateTime.Now.Ticks);
filename = rand.Next() + "." + _suffix;
} fullname = string.Format("{0}\\{1}",updir , filename);
files[].SaveAs(fullname);
var _result = "{\"jsonrpc\" : \"2.0\", \"result\" : null, \"id\" : \"" + filename + "\"}";
System.Web.HttpContext.Current.Response.Write(_result); } public bool IsReusable
{ get
{
return false;
}
}
}
}
第四步:文件辅助类
/// <summary>
///FileHelper 的摘要说明
/// </summary>
public class FileHelper
{ public FileHelper()
{ //
//TODO: 在此处添加构造函数逻辑
//
} /// <summary>
/// 获取上传目录
/// </summary>
/// <returns></returns>
public static string GetUploadPath()
{ string path = HttpContext.Current.Server.MapPath("~/");
string dirname = GetDirName();
string uploadDir = path + "\\" + dirname;
CreateDir(uploadDir);
return uploadDir;
} /// <summary>
/// 获取临时目录
/// </summary>
/// <returns></returns>
public static string GetTempPath()
{ string path = HttpContext.Current.Server.MapPath("~/");
string dirname = GetTempDirName();
string uploadDir = path + "\\" + dirname;
CreateDir(uploadDir);
return uploadDir;
} private static string GetDirName()
{
return System.Configuration.ConfigurationManager.AppSettings["uploaddir"]; } private static string GetTempDirName()
{
return System.Configuration.ConfigurationManager.AppSettings["tempdir"];
} public static void CreateDir(string path)
{
if (!System.IO.Directory.Exists(path))
{ System.IO.Directory.CreateDirectory(path);
}
}
}
第五步,Web.config文件配置信息。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections> <appSettings>
<add key="uploaddir" value="upload" />
<add key="tempdir" value="temp" />
</appSettings> <system.web>
<compilation debug="true" targetFramework="4.0" /> <authentication mode="Windows" />
<httpRuntime maxRequestLength="2147483647" appRequestQueueLimit="1200" executionTimeout="1200"/>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" />
</system.web>
<system.webServer>
<security>
<requestFiltering >
<requestLimits maxAllowedContentLength="2147483647" ></requestLimits>
</requestFiltering>
</security> </system.webServer>
</configuration>
第六步,在进行上传之后,文件保存在对应的日期目录下。如下图。
图 9
WEB版一次选择多个文件进行批量上传(WebUploader)的解决方案的更多相关文章
- WEB版一次选择多个图片进行批量上传(WebUploader)的解决方案
最近在学习百度的开源上传组件WebUploader,上一篇文章,学习了批量文件上传,今天学习一下批量图片上传,实际上与文件上传很类似,只是添加了图片显示功能,这个功能WebUploader组件中已经提 ...
- WEB版一次选择多个文件进行批量上传(Plupload)的解决方案
WEB版一次选择多个文件进行批量上传(Plupload)的解决方案 转载自http://www.cnblogs.com/chillsrc/archive/2013/01/30/2883648.htm ...
- WEB版一次选择多个文件进行批量上传(swfupload)的解决方案
说明:功能完全支持ie和firefox浏览器! 一般的WEB方式文件上传只能使用FileUpload控件进行一个文件一个文件的进行上传,就算是批量上传,也要把文件一个一个的添加到页面,无法如windo ...
- [Plugin] WEB版一次选择多个文件进行批量上传(swfupload)的解决方案
URL:http://www.cnblogs.com/chillsrc/archive/2010/02/21/1670594.html 说明:功能完全支持ie和firefox浏览器! 一般的WEB方式 ...
- Linux svn一次增加多个文件并批量上传
命令行下操作svn没有使用界面形式的TortoiseSVN直观,但是不管怎样,命令行下操作svn还是有它的有点,如果你碰到一次需要svn add许多个文件怎么办?下面的命令可以帮助你解决这个问题 一次 ...
- 【全网首创】修改 Ext.ux.UploadDialog.Dialog 源码支持多选添加文件,批量上传文件
公司老框架的一个页面需要用到文件上传,本以为修改一个配置参数即可解决,百度一番发现都在说这个第三方插件不支持文件多选功能,还有各种各样缺点,暂且不讨论这些吧.先完成领导安排下来的任务. 任务一:支持多 ...
- B/S开发——文件夹的上传和下载
本人在2010年时使用swfupload为核心进行文件的批量上传的解决方案.见文章:WEB版一次选择多个文件进行批量上传(swfupload)的解决方案. 本人在2013年时使用plupload为核心 ...
- uploadify文件批量上传
uploadify能够时间文件的批量上传,JS文件包下载地址,使用说明可以参考官网文档(http://www.uploadify.com/documentation/) 使用方法如下代码: $(&qu ...
- web自动化测试难点 滚动条操作、日期框处理、上传文件
如何把页面滑到最低部? 一般来说,做web自动化测试时,不需要单独写代码,把页面滑到可见,因为click操作,只要是元素存在并且加载出来了,就可以点击到,无需另外写滑动元素的代码. 如果特殊情况需要滑 ...
随机推荐
- JavaScript中的几种继承方式对比
转自:http://blog.csdn.net/kkkkkxiaofei/article/details/46474069 从’严格’意义上说,JavaScript并不是一门真正的面向对象语言.这种说 ...
- 面向Unity程序员的Android快速上手教程
作者:Poan,腾讯移动客户端开发 工程师 商业转载请联系腾讯WeTest获得授权,非商业转载请注明出处. WeTest 导读 随着Unity.cocos2dx等优秀跨平台游戏引擎的出现,开发者可以把 ...
- 【HTML】table元素
1.最简单的table <table> <tr> <th></th> </tr> <tr> <td></td& ...
- Android 性能测试——Heap Viewer 工具
Android 性能测试--Heap Viewer 工具 Heap Viewer能做什么? 实时查看App分配的内存大小和空闲内存大小 发现Memory Leaks Heap Viewer使用条件 5 ...
- 【整理】01. localhost_access_log 记录post请求参数
环境:apache-tomcat-7.0.57 利用Filter过去request请求参数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ...
- Eclipse 改变字体大小,设置背景色
Eclipse背景颜色修改: 操作界面默认颜色为白色.对于我们长期使用电脑编程的人来说,白色很刺激我们的眼睛,所以我经常会改变workspace的背景色,使眼睛舒服一些.设置方法如下: 1.打开win ...
- 方伯伯的玉米田[SCOI2014]
题目描述 方伯伯在自己的农田边散步,他突然发现田里的一排玉米非常的不美.这排玉米一共有N株,它们的高度参差不齐.方伯伯认为单调不下降序列很美,所以他决定先把一些玉米拔高,再把破坏美感的玉米拔除掉,使得 ...
- 一个想法照进现实-《IT连》创业项目:一个转折一个反思
前言: 距离上一篇介绍IT连创业项目的文章,已经过去2个月了,没想到我竟然这么久没写文章向大伙汇报进度了,实在抱歉. 关于这事,我得好好反省,认真检讨,好好写文,哈. 今天主要是讲述一下最近创业的进展 ...
- asp.net mvc项目远程发布到windows server服务器
文章参考 自学MVC看这里——全网最全ASP.NET MVC 教程汇总 图文详解远程部署ASP.NET MVC 5项目 配置Web部署处理程序 设备及环境 一台装有windows server 201 ...
- JAVA WEB主流开发工具下载集
JAVA SEhttp://www.oracle.com/technetwor ... ownloads/index.html eclipsehttp://www.eclipse.org/downlo ...