优化文件上传体验,可以上传多个文件,上传更加流畅

This commit is contained in:
joyqi 2014-02-17 14:38:13 +08:00
parent c056ba70fa
commit b6121f8b75
9 changed files with 13151 additions and 970 deletions

View File

@ -5,28 +5,18 @@ if (isset($post) && $post instanceof Typecho_Widget && $post->have()) {
} else if (isset($page) && $page instanceof Typecho_Widget && $page->have()) {
$fileParentContent = $page;
}
$phpMaxFilesize = function_exists('ini_get') ? trim(ini_get('upload_max_filesize')) : 0;
if (preg_match("/^([0-9]+)([a-z]{1,2})$/i", $phpMaxFilesize, $matches)) {
$phpMaxFilesize = strtolower($matches[1] . $matches[2] . (1 == strlen($matches[2]) ? 'b' : ''));
}
?>
<script src="<?php $options->adminUrl('js/filedrop.js?v=' . $suffixVersion); ?>"></script>
<script src="<?php $options->adminUrl('js/moxie.js?v=' . $suffixVersion); ?>"></script>
<script src="<?php $options->adminUrl('js/plupload.js?v=' . $suffixVersion); ?>"></script>
<script>
$(document).ready(function() {
var errorWord = '<?php $val = function_exists('ini_get') ? trim(ini_get('upload_max_filesize')) : 0;
$last = strtolower($val[strlen($val)-1]);
switch($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
$val = number_format(ceil($val / (1024 *1024)));
_e('文件上传失败, 请确认文件尺寸没有超过 %s 并且服务器文件目录可以写入', "{$val}Mb"); ?>',
loading = $('<img src="<?php $options->adminUrl('img/ajax-loader.gif'); ?>" style="display:none" />')
.appendTo(document.body);
function updateAttacmentNumber () {
var btn = $('#tab-files-btn'),
balloon = $('.balloon', btn),
@ -46,18 +36,46 @@ $(document).ready(function() {
updateAttacmentNumber();
function fileUploadStart (file, id) {
$('<li id="' + id + '" class="loading">'
+ file + '</li>').prependTo('#file-list');
function fileUploadStart (file) {
$('<li id="' + file.id + '" class="loading">'
+ file.name + '</li>').prependTo('#file-list');
}
function fileUploadComplete (id, url, data) {
// 拖拽上传的错误提示
if (!data) {
alert(errorWord);
return;
function fileUploadError (error) {
var file = error.file, code = error.code, word;
switch (code) {
case plupload.FILE_SIZE_ERROR:
word = '<?php _e('文件大小超过限制'); ?>';
break;
case plupload.FILE_EXTENSION_ERROR:
word = '<?php _e('文件扩展名不被支持'); ?>';
break;
case plupload.FILE_DUPLICATE_ERROR:
word = '<?php _e('文件已经上传过'); ?>';
break;
case plupload.HTTP_ERROR:
default:
word = '<?php _e('上传出现错误'); ?>';
break;
}
var fileError = '<?php _e('%s 上传失败'); ?>'.replace('%s', file.name),
li, exist = $('#' + file.id);
if (exist.length > 0) {
li = exist.removeClass('loading').html(fileError);
} else {
li = $('<li>' + fileError + '<br />' + word + '</li>').prependTo('#file-list');
}
li.effect('highlight', {color : '#FBC2C4'}, 2000, function () {
$(this).remove();
});
}
var completeFile = null;
function fileUploadComplete (id, url, data) {
var li = $('#' + id).removeClass('loading').data('cid', data.cid)
.data('url', data.url)
.data('image', data.isImage)
@ -71,122 +89,66 @@ $(document).ready(function() {
attachInsertEvent(li);
attachDeleteEvent(li);
updateAttacmentNumber();
Typecho.uploadComplete(data);
if (!completeFile) {
completeFile = data;
}
}
$('#tab-files').bind('init', function () {
$('.upload-file').fileUpload({
url : '<?php $options->index('/action/upload'
var uploader = new plupload.Uploader({
browse_button : $('.upload-file').get(0),
url : '<?php $options->index('/action/upload'
. (isset($fileParentContent) ? '?cid=' . $fileParentContent->cid : '')); ?>',
types : <?php
$attachmenttypes = $options->allowedattachmenttypes;
$attachmenttypescount = count($attachmenttypes);
$types = array();
for ($i = 0; $i < $attachmenttypescount; $i ++) {
$types[] = '.' . $attachmenttypes[$i];
}
echo json_encode($types);
?>,
typesError : '<?php _e('文件 %s 的类型不被支持'); ?>',
onUpload : fileUploadStart,
onError : function (id) {
$('#' + id).remove();
alert(errorWord);
runtimes : 'html5,flash,silverlight,html4',
flash_swf_url : '<?php $options->adminUrl('js/Moxie.swf'); ?>',
silverlight_swf_url : '<?php $options->adminUrl('js/Moxie.xap'); ?>',
drop_element : $('.upload-area').get(0),
filters : {
max_file_size : '<?php echo $phpMaxFilesize ?>',
mime_types : [{'title' : '<?php _e('允许上传的文件'); ?>', 'extensions' : '<?php echo implode(',', $options->allowedAttachmentTypes); ?>'}],
prevent_duplicates : true
},
onComplete : fileUploadComplete
});
});
$('#upload-panel').filedrop({
url : '<?php $options->index('/action/upload'
. (isset($fileParentContent) ? '?cid=' . $fileParentContent->cid : '')); ?>',
allowedfileextensions : <?php
$attachmenttypes = $options->allowedattachmenttypes;
$attachmenttypescount = count($attachmenttypes);
$types = array();
init : {
FilesAdded : function (up, files) {
plupload.each(files, function(file) {
fileUploadStart(file);
});
for ($i = 0; $i < $attachmenttypescount; $i ++) {
$types[] = '.' . $attachmenttypes[$i];
}
completeFile = null;
uploader.start();
},
echo json_encode($types);
?>,
UploadComplete : function () {
if (completeFile) {
Typecho.uploadComplete(completeFile);
}
},
maxfilesize : <?php
$val = function_exists('ini_get') ? trim(ini_get('upload_max_filesize')) : 0;
$last = strtolower($val[strlen($val)-1]);
switch($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
FileUploaded : function (up, file, result) {
if (200 == result.status) {
var data = $.parseJSON(result.response);
echo ceil($val / (1024 * 1024));
?>,
if (data) {
fileUploadComplete(file.id, data[0], data[1]);
return;
}
}
queuefiles : 5,
fileUploadError({
code : plupload.HTTP_ERROR,
file : file
});
},
error: function(err, file) {
switch(err) {
case 'BrowserNotSupported':
alert('<?php _e('浏览器不支持拖拽上传'); ?>');
break;
case 'TooManyFiles':
alert('<?php _e('一次上传的文件不能多于%d个', 25); ?>');
break;
case 'FileTooLarge':
alert('<?php $val = function_exists('ini_get') ? trim(ini_get('upload_max_filesize')) : 0;
$last = strtolower($val[strlen($val)-1]);
switch($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
$val = number_format(ceil($val / (1024 *1024)));
_e('文件尺寸不能超过 %s', "{$val}Mb"); ?>');
break;
case 'FileTypeNotAllowed':
// The file type is not in the specified list 'allowedfiletypes'
break;
case 'FileExtensionNotAllowed':
alert('<?php _e('文件 %s 的类型不被支持'); ?>'.replace('%s', file.name));
break;
default:
break;
Error : function (up, error) {
fileUploadError(error);
}
}
},
dragOver : function () {
$(this).addClass('drag');
},
});
dragLeave : function () {
$(this).removeClass('drag');
},
drop : function () {
$(this).removeClass('drag');
},
uploadStarted : function (i, file, len) {
fileUploadStart(file.name, 'drag-' + i);
},
uploadFinished : function (i, file, response) {
fileUploadComplete('drag-' + i, response[0], response[1]);
}
uploader.init();
});
function attachInsertEvent (el) {

BIN
admin/js/Moxie.swf Normal file

Binary file not shown.

BIN
admin/js/Moxie.xap Normal file

Binary file not shown.

View File

@ -1,557 +0,0 @@
/*global jQuery:false, alert:false */
/*
* Default text - jQuery plugin for html5 dragging files from desktop to browser
*
* Author: Weixi Yen
*
* Email: [Firstname][Lastname]@gmail.com
*
* Copyright (c) 2010 Resopollution
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* http://www.github.com/weixiyen/jquery-filedrop
*
* Version: 0.1.0
*
* Features:
* Allows sending of extra parameters with file.
* Works with Firefox 3.6+
* Future-compliant with HTML5 spec (will work with Webkit browsers and IE9)
* Usage:
* See README at project homepage
*
*/
;(function($) {
jQuery.event.props.push("dataTransfer");
var default_opts = {
fallback_id: '',
url: '',
refresh: 1000,
paramname: 'userfile',
requestType: 'POST', // just in case you want to use another HTTP verb
allowedfileextensions:[],
allowedfiletypes:[],
maxfiles: 25, // Ignored if queuefiles is set > 0
maxfilesize: 1, // MB file size limit
queuefiles: 0, // Max files before queueing (for large volume uploads)
queuewait: 200, // Queue wait time if full
data: {},
headers: {},
drop: empty,
dragStart: empty,
dragEnter: empty,
dragOver: empty,
dragLeave: empty,
docEnter: empty,
docOver: empty,
docLeave: empty,
beforeEach: empty,
afterAll: empty,
rename: empty,
error: function(err, file, i, status) {
alert(err);
},
uploadOpened: empty,
uploadStarted: empty,
uploadFinished: empty,
progressUpdated: empty,
globalProgressUpdated: empty,
speedUpdated: empty
},
errors = ["BrowserNotSupported", "TooManyFiles", "FileTooLarge", "FileTypeNotAllowed", "NotFound", "NotReadable", "AbortError", "ReadError", "FileExtensionNotAllowed"];
$.fn.filedrop = function(options) {
var opts = $.extend({}, default_opts, options),
global_progress = [],
doc_leave_timer, stop_loop = false,
files_count = 0,
files;
$('#' + opts.fallback_id).css({
display: 'none',
width: 0,
height: 0
});
this.on('drop', drop).on('dragstart', opts.dragStart).on('dragenter', dragEnter).on('dragover', dragOver).on('dragleave', dragLeave);
$(document).on('drop', docDrop).on('dragenter', docEnter).on('dragover', docOver).on('dragleave', docLeave);
this.on('click', function(e){
$('#' + opts.fallback_id).trigger(e);
});
$('#' + opts.fallback_id).change(function(e) {
opts.drop(e);
files = e.target.files;
files_count = files.length;
upload();
});
function drop(e) {
if( opts.drop.call(this, e) === false ) return false;
if(!e.dataTransfer)
return;
files = e.dataTransfer.files;
if (files === null || files === undefined || files.length === 0) {
opts.error(errors[0]);
return false;
}
files_count = files.length;
upload();
e.preventDefault();
return false;
}
function getBuilder(filename, filedata, mime, boundary) {
var dashdash = '--',
crlf = '\r\n',
builder = '',
paramname = opts.paramname;
if (opts.data) {
var params = $.param(opts.data).replace(/\+/g, '%20').split(/&/);
$.each(params, function() {
var pair = this.split("=", 2),
name = decodeURIComponent(pair[0]),
val = decodeURIComponent(pair[1]);
if (pair.length !== 2) {
return;
}
builder += dashdash;
builder += boundary;
builder += crlf;
builder += 'Content-Disposition: form-data; name="' + name + '"';
builder += crlf;
builder += crlf;
builder += val;
builder += crlf;
});
}
if (jQuery.isFunction(paramname)){
paramname = paramname(filename);
}
builder += dashdash;
builder += boundary;
builder += crlf;
builder += 'Content-Disposition: form-data; name="' + (paramname||"") + '"';
builder += '; filename="' + encodeURIComponent(filename) + '"';
builder += crlf;
builder += 'Content-Type: ' + mime;
builder += crlf;
builder += crlf;
builder += filedata;
builder += crlf;
builder += dashdash;
builder += boundary;
builder += dashdash;
builder += crlf;
return builder;
}
function progress(e) {
if (e.lengthComputable) {
var percentage = Math.round((e.loaded * 100) / e.total);
if (this.currentProgress !== percentage) {
this.currentProgress = percentage;
opts.progressUpdated(this.index, this.file, this.currentProgress);
global_progress[this.global_progress_index] = this.currentProgress;
globalProgress();
var elapsed = new Date().getTime();
var diffTime = elapsed - this.currentStart;
if (diffTime >= opts.refresh) {
var diffData = e.loaded - this.startData;
var speed = diffData / diffTime; // KB per second
opts.speedUpdated(this.index, this.file, speed);
this.startData = e.loaded;
this.currentStart = elapsed;
}
}
}
}
function globalProgress() {
if (global_progress.length === 0) {
return;
}
var total = 0, index;
for (index in global_progress) {
if(global_progress.hasOwnProperty(index)) {
total = total + global_progress[index];
}
}
opts.globalProgressUpdated(Math.round(total / global_progress.length));
}
// Respond to an upload
function upload() {
stop_loop = false;
if (!files) {
opts.error(errors[0]);
return false;
}
if (opts.allowedfiletypes.push && opts.allowedfiletypes.length) {
for(var fileIndex = files.length;fileIndex--;) {
if(!files[fileIndex].type || $.inArray(files[fileIndex].type, opts.allowedfiletypes) < 0) {
opts.error(errors[3], files[fileIndex]);
return false;
}
}
}
if (opts.allowedfileextensions.push && opts.allowedfileextensions.length) {
for(var fileIndex = files.length;fileIndex--;) {
var allowedextension = false;
for (i=0;i<opts.allowedfileextensions.length;i++){
if (files[fileIndex].name.substr(files[fileIndex].name.length-opts.allowedfileextensions[i].length) == opts.allowedfileextensions[i]) {
allowedextension = true;
}
}
if (!allowedextension){
opts.error(errors[8], files[fileIndex]);
return false;
}
}
}
var filesDone = 0,
filesRejected = 0;
if (files_count > opts.maxfiles && opts.queuefiles === 0) {
opts.error(errors[1]);
return false;
}
// Define queues to manage upload process
var workQueue = [];
var processingQueue = [];
var doneQueue = [];
// Add everything to the workQueue
for (var i = 0; i < files_count; i++) {
workQueue.push(i);
opts.uploadOpened(i, files[i]);
}
// Helper function to enable pause of processing to wait
// for in process queue to complete
var pause = function(timeout) {
setTimeout(process, timeout);
return;
};
// Process an upload, recursive
var process = function() {
var fileIndex;
if (stop_loop) {
return false;
}
// Check to see if are in queue mode
if (opts.queuefiles > 0 && processingQueue.length >= opts.queuefiles) {
return pause(opts.queuewait);
} else {
// Take first thing off work queue
fileIndex = workQueue[0];
workQueue.splice(0, 1);
// Add to processing queue
processingQueue.push(fileIndex);
}
try {
if (beforeEach(files[fileIndex]) !== false) {
if (fileIndex === files_count) {
return;
}
var reader = new FileReader(),
max_file_size = 1048576 * opts.maxfilesize;
reader.index = fileIndex;
if (files[fileIndex].size > max_file_size) {
opts.error(errors[2], files[fileIndex], fileIndex);
// Remove from queue
processingQueue.forEach(function(value, key) {
if (value === fileIndex) {
processingQueue.splice(key, 1);
}
});
filesRejected++;
return true;
}
reader.onerror = function(e) {
switch(e.target.error.code) {
case e.target.error.NOT_FOUND_ERR:
opts.error(errors[4]);
return false;
case e.target.error.NOT_READABLE_ERR:
opts.error(errors[5]);
return false;
case e.target.error.ABORT_ERR:
opts.error(errors[6]);
return false;
default:
opts.error(errors[7]);
return false;
};
};
reader.onloadend = !opts.beforeSend ? send : function (e) {
opts.beforeSend(files[fileIndex], fileIndex, function () { send(e); });
};
reader.readAsDataURL(files[fileIndex]);
} else {
filesRejected++;
}
} catch (err) {
// Remove from queue
processingQueue.forEach(function(value, key) {
if (value === fileIndex) {
processingQueue.splice(key, 1);
}
});
opts.error(errors[0]);
return false;
}
// If we still have work to do,
if (workQueue.length > 0) {
process();
}
};
var send = function(e) {
var fileIndex = (e.srcElement || e.target).index;
// Sometimes the index is not attached to the
// event object. Find it by size. Hack for sure.
if (e.target.index === undefined) {
e.target.index = getIndexBySize(e.total);
}
var xhr = new XMLHttpRequest(),
upload = xhr.upload,
file = files[e.target.index],
index = e.target.index,
start_time = new Date().getTime(),
boundary = '------multipartformboundary' + (new Date()).getTime(),
global_progress_index = global_progress.length,
builder,
newName = rename(file.name),
mime = file.type;
if (opts.withCredentials) {
xhr.withCredentials = opts.withCredentials;
}
var data = atob(e.target.result.split(',')[1]);
if (typeof newName === "string") {
builder = getBuilder(newName, data, mime, boundary);
} else {
builder = getBuilder(file.name, data, mime, boundary);
}
upload.index = index;
upload.file = file;
upload.downloadStartTime = start_time;
upload.currentStart = start_time;
upload.currentProgress = 0;
upload.global_progress_index = global_progress_index;
upload.startData = 0;
upload.addEventListener("progress", progress, false);
// Allow url to be a method
if (jQuery.isFunction(opts.url)) {
xhr.open(opts.requestType, opts.url(), true);
} else {
xhr.open(opts.requestType, opts.url, true);
}
xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
// Add headers
$.each(opts.headers, function(k, v) {
xhr.setRequestHeader(k, v);
});
xhr.sendAsBinary(builder);
global_progress[global_progress_index] = 0;
globalProgress();
opts.uploadStarted(index, file, files_count);
xhr.onload = function() {
var serverResponse = null;
if (xhr.responseText) {
try {
serverResponse = jQuery.parseJSON(xhr.responseText);
}
catch (e) {
serverResponse = xhr.responseText;
}
}
var now = new Date().getTime(),
timeDiff = now - start_time,
result = opts.uploadFinished(index, file, serverResponse, timeDiff, xhr);
filesDone++;
// Remove from processing queue
processingQueue.forEach(function(value, key) {
if (value === fileIndex) {
processingQueue.splice(key, 1);
}
});
// Add to donequeue
doneQueue.push(fileIndex);
// Make sure the global progress is updated
global_progress[global_progress_index] = 100;
globalProgress();
if (filesDone === (files_count - filesRejected)) {
afterAll();
}
if (result === false) {
stop_loop = true;
}
// Pass any errors to the error option
if (xhr.status < 200 || xhr.status > 299) {
opts.error(xhr.statusText, file, fileIndex, xhr.status);
}
};
};
// Initiate the processing loop
process();
}
function getIndexBySize(size) {
for (var i = 0; i < files_count; i++) {
if (files[i].size === size) {
return i;
}
}
return undefined;
}
function rename(name) {
return opts.rename(name);
}
function beforeEach(file) {
return opts.beforeEach(file);
}
function afterAll() {
return opts.afterAll();
}
function dragEnter(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.dragEnter.call(this, e);
}
function dragOver(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.docOver.call(this, e);
opts.dragOver.call(this, e);
}
function dragLeave(e) {
clearTimeout(doc_leave_timer);
opts.dragLeave.call(this, e);
e.stopPropagation();
}
function docDrop(e) {
e.preventDefault();
opts.docLeave.call(this, e);
return false;
}
function docEnter(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.docEnter.call(this, e);
return false;
}
function docOver(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.docOver.call(this, e);
return false;
}
function docLeave(e) {
doc_leave_timer = setTimeout((function(_this) {
return function() {
opts.docLeave.call(_this, e);
};
})(this), 200);
}
return this;
};
function empty() {}
try {
if (XMLHttpRequest.prototype.sendAsBinary) {
return;
}
XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
function byteValue(x) {
return x.charCodeAt(0) & 0xff;
}
var ords = Array.prototype.map.call(datastr, byteValue);
var ui8a = new Uint8Array(ords);
// Not pretty: Chrome 22 deprecated sending ArrayBuffer, moving instead
// to sending ArrayBufferView. Sadly, no proper way to detect this
// functionality has been discovered. Happily, Chrome 22 also introduced
// the base ArrayBufferView class, not present in Chrome 21.
if ('ArrayBufferView' in window)
this.send(ui8a);
else
this.send(ui8a.buffer);
};
} catch (e) {}
})(jQuery);

10684
admin/js/moxie.js Normal file

File diff suppressed because it is too large Load Diff

2273
admin/js/plupload.js Normal file

File diff suppressed because it is too large Load Diff

View File

@ -160,126 +160,6 @@
return false;
});
};
$.fn.fileUpload = function (options) {
var s = $.extend({
url : null,
onUpload : null,
onComplete : null,
onError : null,
types : [],
name : 'file',
typesError : 'file type error',
single : false
}, options),
p = this.parent().css('position', 'relative'),
input = $('<input class="sr-only" name="' + s.name + '" type="file" />').css({
opacity : 0,
cursor : 'pointer',
position : 'absolute',
width : this.outerWidth(),
height : this.outerHeight(),
left : this.offset().left - p.offset().left,
top : this.offset().top - p.offset().top
}).insertAfter(this), queue = {}, prefix = 'queue-',
index = 0;
window.fileUploadComplete = function (id, url, data) {
if (s.single) {
input.prop('disabled', false);
}
if (!!id && queue[id]) {
queue[id].remove();
delete queue[id];
if (s.onComplete) {
s.onComplete.call(input.get(0), id, url, data);
}
}
};
window.fileUploadError = function (id, word) {
if (s.single) {
input.prop('disabled', false);
}
if (!!id && queue[id]) {
queue[id].remove();
delete queue[id];
if (s.onError) {
s.onError.call(input.get(0), id, word);
}
}
};
function upload (frame, id) {
var form = $('<form action="' + s.url + '" method="post" enctype="multipart/form-data"><input type="hidden" name="_id" value="' + id + '" /></form>'),
replace = input.clone(true).val(''),
io = frame[0],
doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
replace.insertBefore(input);
form.append(input);
$('body', doc).html('').append(form);
input = replace;
form.submit();
}
function checkTypes (file) {
if (!s.types.length) {
return true;
}
file = file.toLowerCase();
for (var i = 0; i < s.types.length; i ++) {
var ext = s.types[i].toLowerCase();
if (file.length <= ext.length) {
continue;
}
if (ext == file.substring(file.length - ext.length)) {
return true;
}
}
return false;
}
input.change(function () {
var t = $(this), file = t.val();
if (!file) {
return;
} else {
file = file.split(/\\|\//).pop();
}
if (!checkTypes(file)) {
alert(s.typesError.replace('%s', file));
return;
}
if (s.single) {
t.prop('disabled', true);
}
var id = prefix + index;
index ++;
queue[id] = $('<iframe style="display:none" id ="upload-'
+ id + '" src="about:blank"></iframe>').appendTo(document.body);
if (s.onUpload) {
s.onUpload.call(this, file, id);
}
upload(queue[id], id);
});
};
})($);

View File

@ -3,6 +3,12 @@ include 'common.php';
include 'header.php';
include 'menu.php';
$phpMaxFilesize = function_exists('ini_get') ? trim(ini_get('upload_max_filesize')) : 0;
if (preg_match("/^([0-9]+)([a-z]{1,2})$/i", $phpMaxFilesize, $matches)) {
$phpMaxFilesize = strtolower($matches[1] . $matches[2] . (1 == strlen($matches[2]) ? 'b' : ''));
}
Typecho_Widget::widget('Widget_Contents_Attachment_Edit')->to($attachment);
?>
@ -42,26 +48,10 @@ Typecho_Widget::widget('Widget_Contents_Attachment_Edit')->to($attachment);
include 'copyright.php';
include 'common-js.php';
?>
<script src="<?php $options->adminUrl('js/filedrop.js?v=' . $suffixVersion); ?>"></script>
<script src="<?php $options->adminUrl('js/moxie.js?v=' . $suffixVersion); ?>"></script>
<script src="<?php $options->adminUrl('js/plupload.js?v=' . $suffixVersion); ?>"></script>
<script type="text/javascript">
$(document).ready(function() {
var errorWord = '<?php $val = function_exists('ini_get') ? trim(ini_get('upload_max_filesize')) : 0;
$last = strtolower($val[strlen($val)-1]);
switch($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
$val = number_format(ceil($val / (1024 *1024)));
_e('文件上传失败, 请确认文件尺寸没有超过 %s 并且服务器文件目录可以写入', "{$val}Mb"); ?>',
loading = $('<img src="<?php $options->adminUrl('img/ajax-loader.gif'); ?>" style="display:none" />')
.appendTo(document.body);
$('#attachment-url').click(function () {
$(this).select();
});
@ -76,10 +66,44 @@ $(document).ready(function() {
return false;
});
function fileUploadStart (file, id) {
function fileUploadStart (file) {
$('<ul id="file-list"></ul>').appendTo('#upload-panel');
$('<li id="' + id + '" class="loading">'
+ file + '</li>').prependTo('#file-list');
$('<li id="' + file.id + '" class="loading">'
+ file.name + '</li>').prependTo('#file-list');
}
function fileUploadError (error) {
var file = error.file, code = error.code, word;
switch (code) {
case plupload.FILE_SIZE_ERROR:
word = '<?php _e('文件大小超过限制'); ?>';
break;
case plupload.FILE_EXTENSION_ERROR:
word = '<?php _e('文件扩展名不被支持'); ?>';
break;
case plupload.FILE_DUPLICATE_ERROR:
word = '<?php _e('文件已经上传过'); ?>';
break;
case plupload.HTTP_ERROR:
default:
word = '<?php _e('上传出现错误'); ?>';
break;
}
var fileError = '<?php _e('%s 上传失败'); ?>'.replace('%s', file.name),
li, exist = $('#' + file.id);
if (exist.length > 0) {
li = exist.removeClass('loading').html(fileError);
} else {
$('<ul id="file-list"></ul>').appendTo('#upload-panel');
li = $('<li>' + fileError + '<br />' + word + '</li>').prependTo('#file-list');
}
li.effect('highlight', {color : '#FBC2C4'}, 2000, function () {
$(this).remove();
});
}
function fileUploadComplete (id, url, data) {
@ -96,97 +120,51 @@ $(document).ready(function() {
});
}
$('.upload-file').fileUpload({
url : '<?php $options->index('/action/upload?do=modify&cid=' . $attachment->cid); ?>',
types : ['.<?php $attachment->attachment->type(); ?>'],
typesError : '<?php _e('文件 %s 的类型与要替换的原文件不一致'); ?>',
onUpload : fileUploadStart,
onError : function (id) {
$('#' + id).remove();
$('#file-list').remove();
alert(errorWord);
},
onComplete : fileUploadComplete
});
$('#upload-panel').filedrop({
var uploader = new plupload.Uploader({
browse_button : $('.upload-file').get(0),
url : '<?php $options->index('/action/upload?do=modify&cid=' . $attachment->cid); ?>',
allowedfileextensions : ['.<?php $attachment->attachment->type(); ?>'],
runtimes : 'html5,flash,silverlight,html4',
flash_swf_url : '<?php $options->adminUrl('js/Moxie.swf'); ?>',
silverlight_swf_url : '<?php $options->adminUrl('js/Moxie.xap'); ?>',
drop_element : $('.upload-area').get(0),
filters : {
max_file_size : '<?php echo $phpMaxFilesize ?>',
mime_types : [{'title' : '<?php _e('允许上传的文件'); ?>', 'extensions' : '<?php $attachment->attachment->type(); ?>'}],
prevent_duplicates : true
},
maxfilesize : <?php
$val = function_exists('ini_get') ? trim(ini_get('upload_max_filesize')) : 0;
$last = strtolower($val[strlen($val)-1]);
switch($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
init : {
FilesAdded : function (up, files) {
plupload.each(files, function(file) {
fileUploadStart(file);
});
echo ceil($val / (1024 * 1024));
?>,
uploader.start();
},
maxfiles : 1,
FileUploaded : function (up, file, result) {
if (200 == result.status) {
var data = $.parseJSON(result.response);
error: function(err, file) {
switch(err) {
case 'BrowserNotSupported':
alert('<?php _e('浏览器不支持拖拽上传'); ?>');
break;
case 'TooManyFiles':
alert('<?php _e('一次只能上传一个文件'); ?>');
break;
case 'FileTooLarge':
alert('<?php $val = function_exists('ini_get') ? trim(ini_get('upload_max_filesize')) : 0;
$last = strtolower($val[strlen($val)-1]);
switch($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
if (data) {
fileUploadComplete(file.id, data[0], data[1]);
return;
}
}
$val = number_format(ceil($val / (1024 *1024)));
_e('文件尺寸不能超过 %s', "{$val}Mb"); ?>');
break;
case 'FileTypeNotAllowed':
// The file type is not in the specified list 'allowedfiletypes'
break;
case 'FileExtensionNotAllowed':
alert('<?php _e('文件 %s 的类型不被支持'); ?>'.replace('%s', file.name));
break;
default:
break;
fileUploadError({
code : plupload.HTTP_ERROR,
file : file
});
},
Error : function (up, error) {
fileUploadError(error);
}
},
dragOver : function () {
$(this).addClass('drag');
},
dragLeave : function () {
$(this).removeClass('drag');
},
drop : function () {
$(this).removeClass('drag');
},
uploadStarted : function (i, file, len) {
fileUploadStart(file.name, 'drag-' + i);
},
uploadFinished : function (i, file, response) {
fileUploadComplete('drag-' + i, response[0], response[1]);
}
});
uploader.init();
});
</script>
<?php

View File

@ -324,41 +324,22 @@ class Widget_Upload extends Widget_Abstract_Contents implements Widget_Interface
/** 增加插件接口 */
$this->pluginHandle()->upload($this);
if ($this->request->isAjax()) {
$this->response->throwJson(array($this->attachment->url, array(
'cid' => $insertId,
'title' => $this->attachment->name,
'type' => $this->attachment->type,
'size' => $this->attachment->size,
'bytes' => number_format(ceil($this->attachment->size / 1024)) . ' Kb',
'isImage' => $this->attachment->isImage,
'url' => $this->attachment->url,
'permalink' => $this->permalink
)));
} else {
echo "<script>parent.fileUploadComplete('" . $this->request->_id
. "', '" . $this->attachment->url . "', " . Json::encode(array(
'cid' => $insertId,
'title' => $this->attachment->name,
'type' => $this->attachment->type,
'size' => $this->attachment->size,
'bytes' => number_format(ceil($this->attachment->size / 1024)) . ' Kb',
'isImage' => $this->attachment->isImage,
'url' => $this->attachment->url,
'permalink' => $this->permalink
)) . ');</script>';
return;
}
$this->response->throwJson(array($this->attachment->url, array(
'cid' => $insertId,
'title' => $this->attachment->name,
'type' => $this->attachment->type,
'size' => $this->attachment->size,
'bytes' => number_format(ceil($this->attachment->size / 1024)) . ' Kb',
'isImage' => $this->attachment->isImage,
'url' => $this->attachment->url,
'permalink' => $this->permalink
)));
}
}
}
if ($this->request->isAjax()) {
$this->response->throwJson(false);
} else {
echo "<script>parent.fileUploadError('" . $this->request->_id . "');</script>";
}
$this->response->throwJson(false);
}
/**
@ -405,41 +386,21 @@ class Widget_Upload extends Widget_Abstract_Contents implements Widget_Interface
/** 增加插件接口 */
$this->pluginHandle()->modify($this);
if ($this->request->isAjax()) {
$this->response->throwJson(array($this->attachment->url, array(
'cid' => $this->cid,
'title' => $this->attachment->name,
'type' => $this->attachment->type,
'size' => $this->attachment->size,
'bytes' => number_format(ceil($this->attachment->size / 1024)) . ' Kb',
'isImage' => $this->attachment->isImage,
'url' => $this->attachment->url,
'permalink' => $this->permalink
)));
} else {
echo "<script>parent.fileUploadComplete('" . $this->request->_id
. "', '" . $this->attachment->url . "', " . Json::encode(array(
'cid' => $this->cid,
'title' => $this->attachment->name,
'type' => $this->attachment->type,
'size' => $this->attachment->size,
'bytes' => number_format(ceil($this->attachment->size / 1024)) . ' Kb',
'isImage' => $this->attachment->isImage,
'url' => $this->attachment->url,
'permalink' => $this->permalink
)) . ');</script>';
return;
}
$this->response->throwJson(array($this->attachment->url, array(
'cid' => $this->cid,
'title' => $this->attachment->name,
'type' => $this->attachment->type,
'size' => $this->attachment->size,
'bytes' => number_format(ceil($this->attachment->size / 1024)) . ' Kb',
'isImage' => $this->attachment->isImage,
'url' => $this->attachment->url,
'permalink' => $this->permalink
)));
}
}
}
if ($this->request->isAjax()) {
$this->response->throwJson(false);
} else {
echo "<script>parent.fileUploadError('" . $this->request->_id . "');</script>";
}
$this->response->throwJson(false);
}
/**