前台代码

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Video.aspx.cs" Inherits="BPMS.WEB.Video" %>

 <!DOCTYPE html>

 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="renderer" content="webkit" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
<title></title>
<script src="/Themes/Scripts/jquery-1.8.2.min.js"></script>
<link rel="stylesheet" type="text/css" href="/ddUpload/css/style.css" />
<script src="/ddUpload/js/resumable.js" charset="utf-8"></script>
</head>
<body> <div id="frame">
&nbsp;<br />
<span style="color: red; font-size: 12px;" id="spanerr"></span>
<div class="resumable-drop" ondragenter="jQuery(this).addClass('resumable-dragover');" ondragend="jQuery(this).removeClass('resumable-dragover');" ondrop="jQuery(this).removeClass('resumable-dragover');">
<a class="resumable-browse" href="#" style="text-decoration: none;">选择视频</a>
</div>
<div class="resumable-progress">
<table>
<tr>
<td width="100%">
<div class="progress-container">
<div class="progress-bar"></div>
</div>
</td>
<td class="progress-text" nowrap="nowrap"></td>
<td class="progress-pause" nowrap="nowrap">
<a href="#" onclick="r.upload(); return(false);" class="progress-resume-link">
<img src="/ddUpload/css/resume.png" title="Resume upload" /></a>
<a href="#" onclick="r.pause(); return(false);" class="progress-pause-link">
<img src="/ddUpload/css/pause.png" title="Pause upload" /></a>
</td>
</tr>
</table>
</div>
<ul class="resumable-list"></ul>
<script>
var r = new Resumable({
target: '/ddUpload/savefile.aspx',
chunkSize: 1 * 1024 * 1024,
simultaneousUploads: 1,
testChunks: false,
throttleProgressCallbacks: 1,
method: "octet"
});
// Resumable.js isn't supported, fall back on a different method
if (!r.support) {
$('.resumable-error').show(); } else {
// Show a place for dropping/selecting files
$('.resumable-drop').show();
r.assignDrop($('.resumable-drop')[0]);
r.assignBrowse($('.resumable-browse')[0]);
var objName = "";
// Handle file add event
r.on('fileAdded', function (file) {
file.startchunkindex = 0; // 设置当前文件开始上传的块数
// Show progress pabr
$('.resumable-progress, .resumable-list').show();
// Show pause, hide resume
$('.resumable-progress .progress-resume-link').hide();
$('.resumable-progress .progress-pause-link').show();
// Add the file to the list
$('.resumable-list').append('<li class="resumable-file-' + file.uniqueIdentifier + '">Uploading <span class="resumable-file-name"></span> <span class="resumable-file-progress"></span>');
$('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-name').html(file.fileName);
objName = file.fileName;
// Actually start the upload
r.upload();
}); r.on('uploadStart', function () {
$('.resumable-progress .progress-resume-link').hide();
$('.resumable-progress .progress-pause-link').show();
});
r.on('pause', function () {
// Show resume, hide pause
$('.resumable-progress .progress-resume-link').show();
$('.resumable-progress .progress-pause-link').hide();
});
r.on('complete', function () {
// Hide pause/resume when the upload has completed
$('.resumable-progress .progress-resume-link, .resumable-progress .progress-pause-link').hide();
$("#spanjindu").html("文件上传完成正在转码!请耐心等候!");
$.ajax({
//请求的路径
url: "/CommonModule/TB_Video/UploadHandler.ashx?action=VideoConvert&FilePath=" + objName,
//请求的方法
type: "post",
dataType: "json",
//请求成功时调用
success: function (msg) {
if (msg["msg"] != "0") {
$("#spanjindu").html("转码完成!请保存数据!");
window.location = "/Video.aspx";
} else {
$("#spanjindu").html("转码失败!请联系相关人员");
}
},
//请求失败时调用
error: function (msg) {
alert(msg);
}
}); });
r.on('fileSuccess', function (file, message) {
// Reflect that the file upload has completed
$('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-progress').html('(completed)');
});
r.on('fileError', function (file, message) {
// Reflect that the file upload has resulted in error
$('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-progress').html('(file could not be uploaded: ' + message + ')');
});
r.on('fileProgress', function (file) {
//alert(file.progress());
// Handle progress for both the file and the overall upload $('.resumable-file-' + file.uniqueIdentifier + ' .resumable-file-progress').html(Math.floor(file.progress() * 100) + '%');
$('.progress-bar').css({ width: Math.floor(r.progress() * 100) + '%' });
});
}
</script>
</div>
<div style="padding-top: 50px; padding-left: 200px;">
<span style="color: blue; font-size: 16px" id="spanjindu"></span>
<br />
视频列表:<br />
<ul>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</ul>
</div> </body>
</html>

后台.cs

 using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; namespace BPMS.WEB
{
public partial class Video : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
load();
}
public void load()
{
int TotalRecord = ; int TotalPage = ;
DataTable dt = new BPMS.Business.GetPageTab().GetTab("SELECT * FROM TB_Video" , , , "ID", "ID", out TotalRecord, out TotalPage);
StringBuilder sb = new StringBuilder();
foreach (DataRow row in dt.Rows)
{
sb.Append("<li style=\"padding:4px 7px 2px 4px\"><a target=\"_blank\" href=\"/play/WebForm1.aspx?path=" + HttpUtility.UrlEncode((row["FilePath"].ToString())) + "\">" + row["FilePath"] + " 观看</a></li>");
}
this.Literal1.Text = sb.ToString();
}
}
}

上传代码

 using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; namespace Html5Upload
{
public partial class savefile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Threading.Thread.Sleep();
Response.AddHeader("Content-Type", "application/json"); if (Request.QueryString["resumableChunkNumber"] != null)
{
string filedir = Request.MapPath("/ddUpload/temp/");
string savefile = filedir+ Request.QueryString["resumableChunkNumber"] + ".lzp";
//Request.Files[0].SaveAs(savefile);
byte[] data = Request.BinaryRead(Request.ContentLength);
using (Stream file = File.Create(savefile))
{
file.Write(data, , data.Length);
file.Close();
} if (Request.QueryString["resumableChunkNumber"] == Request.QueryString["resumableTotalChunks"])
{
MergeFile(filedir, ".lzp", Request.QueryString["resumableFilename"]);
}
} Response.Write("die('{\"jsonrpc\" : \"2.0\", \"result\" : null, \"id\" : \"id\"}');"); } /// <summary>
/// 要合并的文件夹目录
/// </summary>
/// <param name="filePath">文件目录</param>
/// <param name="Extension">扩展名</param>
/// <param name="filename">合并文件名</param>
bool MergeFile(string filePath, string Extension,string filename)
{
bool rBool = false;
//获得当前目录下文件夹列表,按文件名排序
SortedList<int, string> FileList = new SortedList<int, string>();
DirectoryInfo dirInfo = new DirectoryInfo(filePath); foreach (FileSystemInfo var in dirInfo.GetFileSystemInfos())
{
if (var.Attributes != FileAttributes.Directory)
{
if (var.Extension == Extension)
{
FileList.Add(Convert.ToInt32(var.Name.Replace(Extension, "")), var.Name);
}
}
} if (FileList.Count > ) //存在文件
{
FileStream outFile = new FileStream(filePath + "\\" + filename, FileMode.OpenOrCreate, FileAccess.Write);
using (outFile)
{
foreach (int item in FileList.Keys)
{
int data = ;
byte[] buffer = new byte[]; FileStream inFile = new FileStream(filePath + "\\" + FileList[item], FileMode.OpenOrCreate, FileAccess.Read);
using (inFile)
{
while ((data = inFile.Read(buffer, , )) > )
{
outFile.Write(buffer, , data);
}
inFile.Close();
}
}
outFile.Close();
rBool = true; //合并成功
}
} return rBool;
}
}
}

视频转码代码

 using DotNet.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web; namespace BPMS.WEB.CommonModule.TB_Video
{
/// <summary>
/// UploadHandler 的摘要说明
/// </summary>
public class UploadHandler : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Buffer = true;
context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-);
context.Response.AddHeader("pragma", "no-cache");
context.Response.AddHeader("cache-control", "");
context.Response.CacheControl = "no-cache";
string active = HttpContext.Current.Request["action"]; switch (active)
{
//case "Uploadify": //上传文件
// HttpPostedFile file = context.Request.Files["Filedata"];
// string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"]) + "\\";
// if (file != null)
// {
// string _FileName = file.FileName;
// string _FileSize = FileHelper.CountSize(file.ContentLength);
// string _Extension = System.IO.Path.GetExtension(file.FileName).ToLower(); // if (!Directory.Exists(uploadPath))
// {
// Directory.CreateDirectory(uploadPath);
// }
// //+ _Extension
// file.SaveAs(uploadPath + _FileName );
// context.Response.Write("1");
// }
// else
// {
// context.Response.Write("0");
// }
// break;
//case "Delete"://删除文件
// break;
//case "download"://下载 // break;
case "VideoConvert":
VideoConvert(context);
break;
default:
break;
}
} public void VideoConvert(HttpContext context)
{
string FilePath = context.Request["FilePath"];
string path1 = "/ddUpload/temp/" + FilePath;
string path2Name = FilePath.Substring(,FilePath.LastIndexOf('.'))+DateTime.Now.ToString("yyyyMMddHHmmss");
string path2 = "/shuchu/"+path2Name+".flv";
BPMS.WEB.Common.VideoConvert con = new Common.VideoConvert(); bool isok = false;
string houzhui = FilePath.Substring(FilePath.LastIndexOf('.'));
if (houzhui.ToLower() == ".flv")
{
File.Copy(context.Server.MapPath(path1),context.Server.MapPath(path2));
isok = true;
}
else
{
isok = con.ConvertFlv(path1, path2);
} if (isok)
{
BPMS.Business.TB_Video bll = new Business.TB_Video();
BPMS.Entity.TB_Video entity = new BPMS.Entity.TB_Video();
entity.FilePath = path2Name;
//entity.UserID = RequestSession.GetSessionUser().UserId;
//entity.UserName = RequestSession.GetSessionUser().UserName;
bll.Add(entity) ;
context.Response.Write("{\"msg\":\""+path2Name+"\"}");
DeleteSignedFile(context.Server.MapPath("/ddUpload/temp/"), "lzp");
}
else
{
context.Response.Write("{\"msg\":\"0\"}");
}
context.Response.End(); } /// <summary>
/// 删除给定路径下的给定后缀名的文件
/// </summary>
/// <param name="path">传入路径</param>
/// <param name="suffixName">传入后缀名</param>
/// <returns>删除文件列表</returns>
private static string[] DeleteSignedFile(string path, string suffixName)
{
string deletefiles = ""; //记录删除的文件名称 DirectoryInfo di = new DirectoryInfo(path);
//遍历该路径下的所有文件
foreach (FileInfo fi in di.GetFiles())
{
string exname = fi.Name.Substring(fi.Name.LastIndexOf(".") + );//得到后缀名
//判断当前文件后缀名是否与给定后缀名一样
if (exname == suffixName)
{
File.Delete(path + "\\" + fi.Name);//删除当前文件
deletefiles += fi.Name + ",";//追加删除文件列表
}
} if (deletefiles != "")
deletefiles = deletefiles.Substring(, deletefiles.Length - );
return deletefiles.Split(',');//以数组形式返回删除文件列表 } public bool IsReusable
{
get
{
return false;
}
}
}
}

引用js代码

 /*
* MIT Licensed
* http://www.23developer.com/opensource
* http://github.com/23/resumable.js
* Steffen Tiedemann Christensen, steffen@23company.com
*/ (function () {
"use strict"; var Resumable = function (opts) {
if (!(this instanceof Resumable)) {
return new Resumable(opts);
}
this.version = 1.0;
// SUPPORTED BY BROWSER?
// Check if these features are support by the browser:
// - File object type
// - Blob object type
// - FileList object type
// - slicing files
this.support = (
(typeof (File) !== 'undefined') &&
(typeof (Blob) !== 'undefined') &&
(typeof (FileList) !== 'undefined') &&
(!!Blob.prototype.webkitSlice || !!Blob.prototype.mozSlice || !!Blob.prototype.slice || false)
);
if (!this.support) {
//alert("此上传控件兼容 火狐firefox, 谷歌Google Chrome,IE10 以上等浏览器!你的浏览器不支持此上传!");
document.getElementById('spanerr').innerHTML = "提示:此上传控件兼容 火狐firefox, 谷歌Google Chrome,IE10 以上等浏览器!如果是双核模式浏览器,如360,百度,搜狗等浏览器!可切换成谷歌内核(极速模式)!<img src='/ddUpload/css/err.png'/>";
return (false);
} // PROPERTIES
var $ = this;
$.files = [];
$.defaults = {
chunkSize: 1 * 1024 * 1024,
forceChunkSize: false,
simultaneousUploads: 3,
fileParameterName: 'file',
throttleProgressCallbacks: 0.5,
query: {},
headers: {},
preprocess: null,
method: 'multipart',
prioritizeFirstAndLastChunk: false,
target: '/',
testChunks: true,
generateUniqueIdentifier: null,
maxChunkRetries: undefined,
chunkRetryInterval: undefined,
permanentErrors: [404, 415, 500, 501],
maxFiles:1,//undefined,
withCredentials: false,
xhrTimeout: 0,
maxFilesErrorCallback: function (files, errorCount) {
var maxFiles = $.getOpt('maxFiles');
alert('Please upload ' + maxFiles + ' file' + (maxFiles === 1 ? '' : 's') + ' at a time.');
},
minFileSize: 1,
minFileSizeErrorCallback: function (file, errorCount) {
alert(file.fileName || file.name + ' is too small, please upload files larger than ' + $h.formatSize($.getOpt('minFileSize')) + '.');
},
maxFileSize: undefined,
maxFileSizeErrorCallback: function (file, errorCount) {
alert(file.fileName || file.name + ' is too large, please upload files less than ' + $h.formatSize($.getOpt('maxFileSize')) + '.');
},
fileType: ['mp4', 'flv', 'rm', 'rmvb', 'avi', 'wmv', 'mpg', 'mpeg', '3gp', 'swf', 'asf', 'divx', 'xvid', '3gp2', 'flv1', 'mpeg1', 'mpeg2', 'mpeg3', 'mpeg4', 'h264'],
fileTypeErrorCallback: function (file, errorCount) {
//alert(file.fileName || file.name + '' + $.getOpt('fileType') + '.');
document.getElementById('spanjindu').innerHTML = "请上传视频文件!";
//$("#spanjindu").html("请上传视频文件!");
}
};
$.opts = opts || {};
$.getOpt = function (o) {
var $opt = this;
// Get multiple option if passed an array
if (o instanceof Array) {
var options = {};
$h.each(o, function (option) {
options[option] = $opt.getOpt(option);
});
return options;
}
// Otherwise, just return a simple option
if ($opt instanceof ResumableChunk) {
if (typeof $opt.opts[o] !== 'undefined') {
return $opt.opts[o];
} else {
$opt = $opt.fileObj;
}
}
if ($opt instanceof ResumableFile) {
if (typeof $opt.opts[o] !== 'undefined') {
return $opt.opts[o];
} else {
$opt = $opt.resumableObj;
}
}
if ($opt instanceof Resumable) {
if (typeof $opt.opts[o] !== 'undefined') {
return $opt.opts[o];
} else {
return $opt.defaults[o];
}
}
}; // EVENTS
// catchAll(event, ...)
// fileSuccess(file), fileProgress(file), fileAdded(file, event), fileRetry(file), fileError(file, message),
// complete(), progress(), error(message, file), pause()
$.events = [];
$.on = function (event, callback) {
$.events.push(event.toLowerCase(), callback);
};
$.fire = function () {
// `arguments` is an object, not array, in FF, so:
var args = [];
for (var i = 0; i < arguments.length; i++) args.push(arguments[i]);
// Find event listeners, and support pseudo-event `catchAll`
var event = args[0].toLowerCase();
for (var i = 0; i <= $.events.length; i += 2) {
if ($.events[i] == event) $.events[i + 1].apply($, args.slice(1));
if ($.events[i] == 'catchall') $.events[i + 1].apply(null, args);
}
if (event == 'fileerror') $.fire('error', args[2], args[1]);
if (event == 'fileprogress') $.fire('progress');
}; // INTERNAL HELPER METHODS (handy, but ultimately not part of uploading)
var $h = {
stopEvent: function (e) {
e.stopPropagation();
e.preventDefault();
},
each: function (o, callback) {
if (typeof (o.length) !== 'undefined') {
for (var i = 0; i < o.length; i++) {
// Array or FileList
if (callback(o[i]) === false) return;
}
} else {
for (i in o) {
// Object
if (callback(i, o[i]) === false) return;
}
}
},
generateUniqueIdentifier: function (file) {
var custom = $.getOpt('generateUniqueIdentifier');
if (typeof custom === 'function') {
return custom(file);
}
var relativePath = file.webkitRelativePath || file.fileName || file.name; // Some confusion in different versions of Firefox
var size = file.size;
return (size + '-' + relativePath.replace(/[^0-9a-zA-Z_-]/img, ''));
},
contains: function (array, test) {
var result = false; $h.each(array, function (value) {
if (value == test) {
result = true;
return false;
}
return true;
}); return result;
},
formatSize: function (size) {
if (size < 1024) {
return size + ' bytes';
} else if (size < 1024 * 1024) {
return (size / 1024.0).toFixed(0) + ' KB';
} else if (size < 1024 * 1024 * 1024) {
return (size / 1024.0 / 1024.0).toFixed(1) + ' MB';
} else {
return (size / 1024.0 / 1024.0 / 1024.0).toFixed(1) + ' GB';
}
},
getTarget: function (params) {
var target = $.getOpt('target');
if (target.indexOf('?') < 0) {
target += '?';
} else {
target += '&';
}
return target + params.join('&');
}
}; var onDrop = function (event) {
$h.stopEvent(event);
appendFilesFromFileList(event.dataTransfer.files, event);
};
var onDragOver = function (e) {
e.preventDefault();
}; // INTERNAL METHODS (both handy and responsible for the heavy load)
var appendFilesFromFileList = function (fileList, event) {
// check for uploading too many files
var errorCount = 0;
var o = $.getOpt(['maxFiles', 'minFileSize', 'maxFileSize', 'maxFilesErrorCallback', 'minFileSizeErrorCallback', 'maxFileSizeErrorCallback', 'fileType', 'fileTypeErrorCallback']);
if (typeof (o.maxFiles) !== 'undefined' && o.maxFiles < (fileList.length + $.files.length)) {
// if single-file upload, file is already added, and trying to add 1 new file, simply replace the already-added file
if (o.maxFiles === 1 && $.files.length === 1 && fileList.length === 1) {
$.removeFile($.files[0]);
} else {
o.maxFilesErrorCallback(fileList, errorCount++);
return false;
}
}
var files = [];
$h.each(fileList, function (file) {
var fileName = file.name.split('.');
var fileType = fileName[fileName.length - 1].toLowerCase(); if (o.fileType.length > 0 && !$h.contains(o.fileType, fileType)) {
o.fileTypeErrorCallback(file, errorCount++);
return false;
} if (typeof (o.minFileSize) !== 'undefined' && file.size < o.minFileSize) {
o.minFileSizeErrorCallback(file, errorCount++);
return false;
}
if (typeof (o.maxFileSize) !== 'undefined' && file.size > o.maxFileSize) {
o.maxFileSizeErrorCallback(file, errorCount++);
return false;
} // directories have size == 0
if (!$.getFromUniqueIdentifier($h.generateUniqueIdentifier(file))) {
(function () {
var f = new ResumableFile($, file);
window.setTimeout(function () {
$.files.push(f);
files.push(f);
f.container = (typeof event != 'undefined' ? event.srcElement : null);
$.fire('fileAdded', f, event)
}, 0);
})()
};
});
window.setTimeout(function () {
$.fire('filesAdded', files)
}, 0);
}; // INTERNAL OBJECT TYPES
function ResumableFile(resumableObj, file) {
var $ = this;
$.opts = {};
$.getOpt = resumableObj.getOpt;
$._prevProgress = 0;
$.resumableObj = resumableObj;
$.file = file;
$.fileName = file.fileName || file.name; // Some confusion in different versions of Firefox
$.size = file.size;
$.relativePath = file.webkitRelativePath || $.fileName;
$.uniqueIdentifier = $h.generateUniqueIdentifier(file);
$._pause = false;
$.container = '';
$.startchunkindex = 0; var _error = false; // Callback when something happens within the chunk
var chunkEvent = function (event, message) {
// event can be 'progress', 'success', 'error' or 'retry'
switch (event) {
case 'progress':
$.resumableObj.fire('fileProgress', $);
break;
case 'error':
$.abort();
_error = true;
$.chunks = [];
$.resumableObj.fire('fileError', $, message);
break;
case 'success':
if (_error) return;
$.resumableObj.fire('fileProgress', $); // it's at least progress
if ($.isComplete()) {
$.resumableObj.fire('fileSuccess', $, message);
}
break;
case 'retry':
$.resumableObj.fire('fileRetry', $);
break;
}
}; // Main code to set up a file object with chunks,
// packaged to be able to handle retries if needed.
$.chunks = [];
$.abort = function () {
// Stop current uploads
var abortCount = 0;
$h.each($.chunks, function (c) {
if (c.status() == 'uploading') {
c.abort();
abortCount++;
}
});
if (abortCount > 0) $.resumableObj.fire('fileProgress', $);
};
$.cancel = function () {
// Reset this file to be void
var _chunks = $.chunks;
$.chunks = [];
// Stop current uploads
$h.each(_chunks, function (c) {
if (c.status() == 'uploading') {
c.abort();
$.resumableObj.uploadNextChunk();
}
});
$.resumableObj.removeFile($);
$.resumableObj.fire('fileProgress', $);
};
$.retry = function () {
$.bootstrap();
var firedRetry = false;
$.resumableObj.on('chunkingComplete', function () {
if (!firedRetry) $.resumableObj.upload();
firedRetry = true;
});
};
$.bootstrap = function () {
$.abort();
_error = false;
// Rebuild stack of chunks from file
$.chunks = [];
$._prevProgress = 0;
var round = $.getOpt('forceChunkSize') ? Math.ceil : Math.floor;
var maxOffset = Math.max(round($.file.size / $.getOpt('chunkSize')), 1);
for (var offset = 0; offset < maxOffset; offset++) {
(function (offset) {
window.setTimeout(function () {
$.chunks.push(new ResumableChunk($.resumableObj, $, offset, chunkEvent));
$.resumableObj.fire('chunkingProgress', $, offset / maxOffset);
}, 0);
})(offset)
}
window.setTimeout(function () {
$.resumableObj.fire('chunkingComplete', $);
}, 0);
};
$.progress = function () {
if (_error) return (1);
// Sum up progress across everything
var ret = 0;
var error = false;
$h.each($.chunks, function (c) {
if (c.status($.startchunkindex) == 'error') error = true;
ret += c.progress(true, $.startchunkindex); // get chunk progress relative to entire file
//console.info(c.progress(true,$.startchunkindex));
});
ret = (error ? 1 : (ret > 0.999 ? 1 : ret));
ret = Math.max($._prevProgress, ret); // We don't want to lose percentages when an upload is paused
$._prevProgress = ret;
return (ret);
};
$.isUploading = function () {
var uploading = false;
$h.each($.chunks, function (chunk) {
if (chunk.status() == 'uploading') {
uploading = true;
return (false);
}
});
return (uploading);
};
$.isComplete = function () {
var outstanding = false;
$h.each($.chunks, function (chunk) {
var status = chunk.status();
if (status == 'pending' || status == 'uploading' || chunk.preprocessState === 1) {
outstanding = true;
return (false);
}
});
return (!outstanding);
};
$.pause = function (pause) {
if (typeof (pause) === 'undefined') {
$._pause = ($._pause ? false : true);
} else {
$._pause = pause;
}
};
$.isPaused = function () {
return $._pause;
}; // Bootstrap and return
$.resumableObj.fire('chunkingStart', $);
$.bootstrap();
return (this);
} function ResumableChunk(resumableObj, fileObj, offset, callback) {
var $ = this;
$.opts = {};
$.getOpt = resumableObj.getOpt;
$.resumableObj = resumableObj;
$.fileObj = fileObj;
$.fileObjSize = fileObj.size;
$.fileObjType = fileObj.file.type;
$.offset = offset;
$.callback = callback;
$.lastProgressCallback = (new Date);
$.tested = false;
$.retries = 0;
$.pendingRetry = false;
$.preprocessState = 0; // 0 = unprocessed, 1 = processing, 2 = finished // Computed properties
var chunkSize = $.getOpt('chunkSize');
$.loaded = 0;
$.startByte = $.offset * chunkSize;
$.endByte = Math.min($.fileObjSize, ($.offset + 1) * chunkSize);
if ($.fileObjSize - $.endByte < chunkSize && !$.getOpt('forceChunkSize')) {
// The last chunk will be bigger than the chunk size, but less than 2*chunkSize
$.endByte = $.fileObjSize;
}
$.xhr = null; // test() makes a GET request without any data to see if the chunk has already been uploaded in a previous session
$.test = function () {
// Set up request and listen for event
$.xhr = new XMLHttpRequest(); var testHandler = function (e) {
$.tested = true;
var status = $.status();
if (status == 'success') {
$.callback(status, $.message());
$.resumableObj.uploadNextChunk();
} else {
$.send();
}
};
$.xhr.addEventListener('load', testHandler, false);
$.xhr.addEventListener('error', testHandler, false); // Add data from the query options
var params = [];
var customQuery = $.getOpt('query');
if (typeof customQuery == 'function') customQuery = customQuery($.fileObj, $);
$h.each(customQuery, function (k, v) {
params.push([encodeURIComponent(k), encodeURIComponent(v)].join('='));
});
// Add extra data to identify chunk
params.push(['resumableChunkNumber', encodeURIComponent($.offset + 1)].join('='));
params.push(['resumableChunkSize', encodeURIComponent($.getOpt('chunkSize'))].join('='));
params.push(['resumableCurrentChunkSize', encodeURIComponent($.endByte - $.startByte)].join('='));
params.push(['resumableTotalSize', encodeURIComponent($.fileObjSize)].join('='));
params.push(['resumableType', encodeURIComponent($.fileObjType)].join('='));
params.push(['resumableIdentifier', encodeURIComponent($.fileObj.uniqueIdentifier)].join('='));
params.push(['resumableFilename', encodeURIComponent($.fileObj.fileName)].join('='));
params.push(['resumableRelativePath', encodeURIComponent($.fileObj.relativePath)].join('='));
params.push(['resumableTotalChunks', encodeURIComponent($.fileObj.chunks.length)].join('='));
// Append the relevant chunk and send it
$.xhr.open('GET', $h.getTarget(params));
$.xhr.timeout = $.getOpt('xhrTimeout');
$.xhr.withCredentials = $.getOpt('withCredentials');
// Add data from header options
$h.each($.getOpt('headers'), function (k, v) {
$.xhr.setRequestHeader(k, v);
});
$.xhr.send(null);
}; $.preprocessFinished = function () {
$.preprocessState = 2;
$.send();
}; // send() uploads the actual data in a POST call
$.send = function () {
var preprocess = $.getOpt('preprocess');
if (typeof preprocess === 'function') {
switch ($.preprocessState) {
case 0:
preprocess($);
$.preprocessState = 1;
return;
case 1:
return;
case 2:
break;
}
}
if ($.getOpt('testChunks') && !$.tested) {
$.test();
return;
} // Set up request and listen for event
$.xhr = new XMLHttpRequest(); // Progress
$.xhr.upload.addEventListener('progress', function (e) {
if ((new Date) - $.lastProgressCallback > $.getOpt('throttleProgressCallbacks') * 1000) {
$.callback('progress');
$.lastProgressCallback = (new Date);
}
$.loaded = e.loaded || 0;
}, false);
$.loaded = 0;
$.pendingRetry = false;
$.callback('progress'); // Done (either done, failed or retry)
var doneHandler = function (e) {
var status = $.status();
if (status == 'success' || status == 'error') {
$.callback(status, $.message());
$.resumableObj.uploadNextChunk();
} else {
$.callback('retry', $.message());
$.abort();
$.retries++;
var retryInterval = $.getOpt('chunkRetryInterval');
if (retryInterval !== undefined) {
$.pendingRetry = true;
setTimeout($.send, retryInterval);
} else {
$.send();
}
}
};
$.xhr.addEventListener('load', doneHandler, false);
$.xhr.addEventListener('error', doneHandler, false); // Set up the basic query data from Resumable
var query = {
resumableChunkNumber: $.offset + 1,
resumableChunkSize: $.getOpt('chunkSize'),
resumableCurrentChunkSize: $.endByte - $.startByte,
resumableTotalSize: $.fileObjSize,
resumableType: $.fileObjType,
resumableIdentifier: $.fileObj.uniqueIdentifier,
resumableFilename: $.fileObj.fileName,
resumableRelativePath: $.fileObj.relativePath,
resumableTotalChunks: $.fileObj.chunks.length
};
// Mix in custom data
var customQuery = $.getOpt('query');
if (typeof customQuery == 'function') customQuery = customQuery($.fileObj, $);
$h.each(customQuery, function (k, v) {
query[k] = v;
}); var func = ($.fileObj.file.slice ? 'slice' : ($.fileObj.file.mozSlice ? 'mozSlice' : ($.fileObj.file.webkitSlice ? 'webkitSlice' : 'slice'))),
bytes = $.fileObj.file[func]($.startByte, $.endByte),
data = null,
target = $.getOpt('target'); if ($.getOpt('method') === 'octet') {
// Add data from the query options
data = bytes;
var params = [];
$h.each(query, function (k, v) {
params.push([encodeURIComponent(k), encodeURIComponent(v)].join('='));
});
target = $h.getTarget(params);
} else {
// Add data from the query options
data = new FormData();
$h.each(query, function (k, v) {
data.append(k, v);
});
data.append($.getOpt('fileParameterName'), bytes);
} $.xhr.open('POST', target);
$.xhr.timeout = $.getOpt('xhrTimeout');
$.xhr.withCredentials = $.getOpt('withCredentials');
// Add data from header options
$h.each($.getOpt('headers'), function (k, v) {
$.xhr.setRequestHeader(k, v);
});
$.xhr.send(data);
};
$.abort = function () {
// Abort and reset
if ($.xhr) $.xhr.abort();
$.xhr = null;
};
$.status = function (startchunkindex) { if ($.offset < startchunkindex) {
// console.info($.offset+'success');
return ('success'); } // Returns: 'pending', 'uploading', 'success', 'error'
if ($.pendingRetry) {
// if pending retry then that's effectively the same as actively uploading,
// there might just be a slight delay before the retry starts
return ('uploading');
} else if (!$.xhr) {
return ('pending');
} else if ($.xhr.readyState < 4) {
// Status is really 'OPENED', 'HEADERS_RECEIVED' or 'LOADING' - meaning that stuff is happening
return ('uploading');
} else { if ($.xhr.status == 200) {
// HTTP 200, perfect
return ('success');
} else if ($h.contains($.getOpt('permanentErrors'), $.xhr.status) || $.retries >= $.getOpt('maxChunkRetries')) {
// HTTP 415/500/501, permanent error
return ('error');
} else {
// this should never happen, but we'll reset and queue a retry
// a likely case for this would be 503 service unavailable
$.abort();
return ('pending');
}
}
};
$.message = function () {
return ($.xhr ? $.xhr.responseText : '');
};
$.progress = function (relative, startchunkindex) {
if (typeof (relative) === 'undefined') relative = false;
var factor = (relative ? ($.endByte - $.startByte) / $.fileObjSize : 1);
if ($.pendingRetry) return (0);
var s = $.status(startchunkindex);
switch (s) {
case 'success':
case 'error':
return (1 * factor);
case 'pending':
return (0 * factor);
default:
return ($.loaded / ($.endByte - $.startByte) * factor);
}
};
return (this);
} // QUEUE
$.uploadNextChunk = function () {
var found = false; // In some cases (such as videos) it's really handy to upload the first
// and last chunk of a file quickly; this let's the server check the file's
// metadata and determine if there's even a point in continuing.
if ($.getOpt('prioritizeFirstAndLastChunk')) {
$h.each($.files, function (file) {
if (file.chunks.length && file.chunks[0].status() == 'pending' && file.chunks[0].preprocessState === 0) {
file.chunks[0].send();
found = true;
return (false);
}
if (file.chunks.length > 1 && file.chunks[file.chunks.length - 1].status() == 'pending' && file.chunks[file.chunks.length - 1].preprocessState === 0) {
file.chunks[file.chunks.length - 1].send();
found = true;
return (false);
}
});
if (found) return (true);
} // Now, simply look for the next, best thing to upload
$h.each($.files, function (file) {
if (file.isPaused() === false) {
// $h.each(file.chunks, function(chunk){
// if(chunk.status()=='pending' && chunk.preprocessState === 0) {
// chunk.send();
// found = true;
// return(false);
// }
// });
for (var i = file.startchunkindex; i < file.chunks.length; i++) { if (file.chunks[i].status() == 'pending' && file.chunks[i].preprocessState === 0) {
file.chunks[i].send();
found = true;
return (false);
} }; }
if (found) return (false);
});
if (found) return (true); // The are no more outstanding chunks to upload, check is everything is done
var outstanding = false;
$h.each($.files, function (file) {
if (!file.isComplete()) {
outstanding = true;
return (false);
}
});
if (!outstanding) {
// All chunks have been uploaded, complete
$.fire('complete');
}
return (false);
}; // PUBLIC METHODS FOR RESUMABLE.JS
$.assignBrowse = function (domNodes, isDirectory) {
if (typeof (domNodes.length) == 'undefined') domNodes = [domNodes]; $h.each(domNodes, function (domNode) {
var input;
if (domNode.tagName === 'INPUT' && domNode.type === 'file') {
input = domNode;
} else {
input = document.createElement('input');
input.setAttribute('type', 'file');
input.style.display = 'none';
domNode.addEventListener('click', function () {
input.style.opacity = 0;
input.style.display = 'block';
input.focus();
input.click();
input.style.display = 'none';
}, false);
domNode.appendChild(input);
}
var maxFiles = $.getOpt('maxFiles');
if (typeof (maxFiles) === 'undefined' || maxFiles != 1) {
input.setAttribute('multiple', 'multiple');
} else {
input.removeAttribute('multiple');
}
if (isDirectory) {
input.setAttribute('webkitdirectory', 'webkitdirectory');
} else {
input.removeAttribute('webkitdirectory');
}
// When new files are added, simply append them to the overall list
input.addEventListener('change', function (e) {
appendFilesFromFileList(e.target.files, e);
e.target.value = '';
}, false);
});
};
$.assignDrop = function (domNodes) {
if (typeof (domNodes.length) == 'undefined') domNodes = [domNodes]; $h.each(domNodes, function (domNode) {
domNode.addEventListener('dragover', onDragOver, false);
domNode.addEventListener('drop', onDrop, false);
});
};
$.unAssignDrop = function (domNodes) {
if (typeof (domNodes.length) == 'undefined') domNodes = [domNodes]; $h.each(domNodes, function (domNode) {
domNode.removeEventListener('dragover', onDragOver);
domNode.removeEventListener('drop', onDrop);
});
};
$.isUploading = function () {
var uploading = false;
$h.each($.files, function (file) {
if (file.isUploading()) {
uploading = true;
return (false);
}
});
return (uploading);
};
$.upload = function () {
// Make sure we don't start too many uploads at once
if ($.isUploading()) return;
// Kick off the queue
$.fire('uploadStart');
for (var num = 1; num <= $.getOpt('simultaneousUploads') ; num++) {
$.uploadNextChunk();
}
};
$.pause = function () {
// Resume all chunks currently being uploaded
$h.each($.files, function (file) {
file.abort();
});
$.fire('pause');
};
$.cancel = function () {
for (var i = $.files.length - 1; i >= 0; i--) {
$.files[i].cancel();
}
$.fire('cancel');
};
$.progress = function () {
var totalDone = 0;
var totalSize = 0;
// Resume all chunks currently being uploaded
$h.each($.files, function (file) {
totalDone += file.progress() * file.size;
totalSize += file.size;
});
return (totalSize > 0 ? totalDone / totalSize : 0);
};
$.addFile = function (file, event) {
appendFilesFromFileList([file], event);
};
$.removeFile = function (file) {
for (var i = $.files.length - 1; i >= 0; i--) {
if ($.files[i] === file) {
$.files.splice(i, 1);
}
}
};
$.getFromUniqueIdentifier = function (uniqueIdentifier) {
var ret = false;
$h.each($.files, function (f) {
if (f.uniqueIdentifier == uniqueIdentifier) ret = f;
});
return (ret);
};
$.getSize = function () {
var totalSize = 0;
$h.each($.files, function (file) {
totalSize += file.size;
});
return (totalSize);
}; return (this);
}; // Node.js-style export for Node and Component
if (typeof module != 'undefined') {
module.exports = Resumable;
} else if (typeof define === "function" && define.amd) {
// AMD/requirejs: Define the module
define(function () {
return Resumable;
});
} else {
// Browser: Expose to window
window.Resumable = Resumable;
} })();

css 代码

 /* Reset */
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td{margin:;padding:;}table{border-collapse:collapse;border-spacing:;}fieldset,img{border:;}address,caption,cite,code,dfn,th,var{font-style:normal;font-weight:normal;}ol,ul {list-style:none;}caption,th {text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym {border:;} /* Baseline */
body, p, h1, h2, h3, h4, h5, h6 {font:normal 12px/1.3em Helvetica, Arial, sans-serif; color:#333; }
h1 {font-size:22px; font-weight:bold;}
h2 {font-size:19px; font-weight:bold;}
h3 {font-size:16px; font-weight:bold;}
h4 {font-size:14px; font-weight:bold;}
h5 {font-size:12px; font-weight:bold;}
p {margin:10px 0;} /*body {text-align:center; margin:40px;}*/
#frame {margin:0 auto; width:560px; text-align:left;} /* Uploader: Drag & Drop */
.resumable-error {display:none; font-size:14px; font-style:italic;}
.resumable-drop {padding:10px; font-size:16px; text-align:left; color:#666; font-weight:bold;background-color:#eee; border:2px dashed #aaa; border-radius:10px; margin-top:20px; z-index:; height:20px; width:70px;}
.resumable-dragover {padding:30px; color:#555; background-color:#ddd; border:1px solid #999;} /* Uploader: Progress bar */
.resumable-progress {margin:30px 0 30px 0; width:100%; display:none;}
.progress-container {height:7px; background:#9CBD94; position:relative; }
.progress-bar {position:absolute; top:; left:; bottom:; background:#45913A; width:;}
.progress-text {font-size:11px; line-height:9px; padding-left:10px;}
.progress-pause {padding:0 0 0 7px;}
.progress-resume-link {display:none;}
.is-paused .progress-resume-link {display:inline;}
.is-paused .progress-pause-link {display:none;}
.is-complete .progress-pause {display:none;} /* Uploader: List of items being uploaded */
.resumable-list {overflow:auto; margin-right:-20px; display:none;}
.uploader-item {width:148px; height:90px; background-color:#666; position:relative; border:2px solid black; float:left; margin:0 6px 6px 0;}
.uploader-item-thumbnail {width:100%; height:100%; position:absolute; top:; left:;}
.uploader-item img.uploader-item-thumbnail {opacity:;}
.uploader-item-creating-thumbnail {padding:0 5px; font-size:9px; color:white;}
.uploader-item-title {position:absolute; font-size:9px; line-height:11px; padding:3px 50px 3px 5px; bottom:; left:; right:; color:white; background-color:rgba(0,0,0,0.6); min-height:27px;}
.uploader-item-status {position:absolute; bottom:3px; right:3px;} /* Uploader: Hover & Active status */
.uploader-item:hover, .is-active .uploader-item {border-color:#4a873c; cursor:pointer; }
.uploader-item:hover .uploader-item-title, .is-active .uploader-item .uploader-item-title {background-color:rgba(74,135,60,0.8);} /* Uploader: Error status */
.is-error .uploader-item:hover, .is-active.is-error .uploader-item {border-color:#900;}
.is-error .uploader-item:hover .uploader-item-title, .is-active.is-error .uploader-item .uploader-item-title {background-color:rgba(153,0,0,0.6);}
.is-error .uploader-item-creating-thumbnail {display:none;}

图片 resume.png

图片pause.png

使用resumable.js上传大文件(视频)兵转换flv格式的更多相关文章

  1. JS上传大文件的解决方案

    最近遇见一个需要上传百兆大文件的需求,调研了七牛和腾讯云的切片分段上传功能,因此在此整理前端大文件上传相关功能的实现. 在某些业务中,大文件上传是一个比较重要的交互场景,如上传入库比较大的Excel表 ...

  2. 百度Fex webuploader.js上传大文件失败

    项目上用百度webuploader.js上传文件,option选项里面已经设置单个文件大小,但是上传低于此阈值的文件时仍然不成功. 我现在的理解是,框架是将文件post到后台服务器端的.. 百度发现是 ...

  3. JS原生上传大文件显示进度条-php上传文件

    JS原生上传大文件显示进度条-php上传文件 在php.ini修改需要的大小: upload_max_filesize = 8M    post_max_size = 10M    memory_li ...

  4. tp5+layui 实现上传大文件

    前言: 之前所写的文件上传类通常进行考虑的是文件的类型.大小是否符合要求条件.当上传大文件时就要考虑到php的配置和服务器的配置问题.之前简单的觉得只要将php.ini中的表单上传的 大小,单脚本执行 ...

  5. SWFUpload上传大文件(暂时用用,真正用的时候还是要改的)

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  6. ASP.NET 使用 plupload 上传大文件时出现“blob”文件的Bug

    最近在一个ASP.NET 项目中使用了plupload来上传文件,结果几天后客户发邮件说上传的文件不对,说是文件无法打开 在进入系统进行查看后发现上传的文件竟然没有后缀,经过一番测试发现如果文件上传的 ...

  7. WEB上传大文件解决方案

    众所皆知,web上传大文件,一直是一个痛.上传文件大小限制,页面响应时间超时.这些都是web开发所必须直面的. 本文给出的解决方案是:前端实现数据流分片长传,后面接收完毕后合并文件的思路.下面贴出简易 ...

  8. Asp.Net上传大文件带进度条swfupload

    Asp.Net基于swfupload上传大文件带进度条百分比显示,漂亮大气上档次,大文件无压力,先看效果 一.上传效果图 1.上传前界面:图片不喜欢可以自己换 2.上传中界面:百分比显示 3.上传后返 ...

  9. tornado上传大文件以及多文件上传

    tornado上传大文件问题解决方法 tornado默认上传限制为低于100M,但是由于需要上传大文件需求,网上很多说是用nginx,但我懒,同时不想在搞一个服务了. 解决方法: server = H ...

随机推荐

  1. 软交换和IMS是什么关系

    软交换是一种功能实体,为下一代网络NGN提供具有实时性要求的业务的呼叫控制和连接控制功能,是下一代网络呼叫与控制的核心. 简单地看,软交换是实现传统程控交换机的"呼叫控制"功能的实 ...

  2. Appium Android定位元素与操作

    文章写得很好,转载备用 一.常用识别元素的工具 uiautomator:Android SDK自带的一个工具,在tools目录下 monitor:Android SDK自带的一个工具,在tools目录 ...

  3. Info.plist和pch文件的作用

  4. ios开发 数据库版本迁移手动更新迭代和自动更新迭代

    数据库版本迁移顾名思义就是在原有的数据库中更新数据库,数据库中的数据保持不变对表的增.删.该.查. 数据持久化存储: plist文件(属性列表) preference(偏好设置) NSKeyedArc ...

  5. 解决下载Android Build-tools 19.1.0失败

    准备从Eclipse转到Android Studio了.今天尝试Android Studio的时候,被它提醒我SDK的Android Build-tools版本过低,需要升级. 于是打开Android ...

  6. spring3.2.2+mybatis3.2.3+c3p0项目整合

    国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送)国内私 ...

  7. Spring 3 MVC and JSON example

    国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送)国内私 ...

  8. PowerShell远程安装应用程序

    安装MSI包 使用PowerShell调用WMI对象,你可以执行下面的脚本来安装你的MSI安装包: $box="deviis01" #this is the name of you ...

  9. [React] Higher Order Components (replaces Mixins)

    Higher order components will allow you to apply behaviors to multiple React components. So the idea ...

  10. extremeComponents(ec)源码分析

    eXtremeComponents(简称ec)是一系列提供高级显示的开源JSP定制标签,当前的包含的组件为eXtremeTable,用于以表形式显示数据. 其本质是jsp的自定义标签,抓住这一点就抓住 ...