Remove codes related to old uploader

This commit is contained in:
HFO4 2022-04-17 10:44:58 +08:00
parent 8bac9a4abb
commit 1853ff539b
23 changed files with 75 additions and 32205 deletions

View File

@ -1,40 +0,0 @@
// Chinese (China) (zh_CN)
plupload.addI18n({
"Stop Upload": "停止上传",
"Upload URL might be wrong or doesn't exist.":
"上传的URL可能是错误的或不存在。",
tb: "tb",
Size: "大小",
Close: "关闭",
"Init error.": "初始化错误。",
"Add files to the upload queue and click the start button.":
"将文件添加到上传队列,然后点击”开始上传“按钮。",
Filename: "文件名",
"Image format either wrong or not supported.": "图片格式错误或者不支持。",
Status: "状态",
"HTTP Error.": "HTTP 错误。",
"Start Upload": "开始上传",
mb: "mb",
kb: "kb",
"Duplicate file error.": "重复文件错误。",
"File size error.": "文件大小错误。",
"N/A": "N/A",
gb: "gb",
"Error: Invalid file extension:": "错误:无效的文件扩展名:",
"Select files": "选择文件",
"%s already present in the queue.": "%s 已经在当前队列里。",
"File: %s": "文件: %s",
b: "b",
"Uploaded %d/%d files": "已上传 %d/%d 个文件",
"Upload element accepts only %d file(s) at a time. Extra files were stripped.":
"每次只接受同时上传 %d 个文件,多余的文件将会被删除。",
"%d files queued": "%d 个文件加入到队列",
"File: %s, size: %d, max file size: %d":
"文件: %s, 大小: %d, 最大文件大小: %d",
"Drag files here.": "把文件拖到这里。",
"Runtime ran out of available memory.": "运行时已消耗所有可用内存。",
"File count error.": "文件数量错误。",
"File extension error.": "文件扩展名错误。",
"Error: File too large:": "错误: 文件太大:",
"Add Files": "增加文件",
});

View File

@ -1,268 +0,0 @@
// /*global Qiniu */
// /*global plupload */
// /*global FileProgress */
// /*global hljs */
// function getCookieByString(cookieName){
// var start = document.cookie.indexOf(cookieName+'=');
// if (start == -1) return false;
// start = start+cookieName.length+1;
// var end = document.cookie.indexOf(';', start);
// if (end == -1) end=document.cookie.length;
// return document.cookie.substring(start, end);
// }
// if(uploadConfig.saveType == "oss" || uploadConfig.saveType == "upyun" || uploadConfig.saveType == "s3"){
// ChunkSize = "0";
// }else{
// ChunkSize = "4mb";
// }
// uploader = Qiniu.uploader({
// runtimes: 'html5,flash,html4',
// browse_button: 'pickfiles',
// container: 'container',
// drop_element: 'container',
// max_file_size: uploadConfig.maxSize,
// flash_swf_url: '/bower_components/plupload/js/Moxie.swf',
// dragdrop: true,
// chunk_size: ChunkSize,
// filters: {
// mime_types :uploadConfig.allowedType,
// },
// multi_selection: !(moxie.core.utils.Env.OS.toLowerCase() === "ios"),
// uptoken_url: "/Upload/Token",
// // uptoken_func: function(){
// // var ajax = new XMLHttpRequest();
// // ajax.open('GET', $('#uptoken_url').val(), false);
// // ajax.setRequestHeader("If-Modified-Since", "0");
// // ajax.send();
// // if (ajax.status === 200) {
// // var res = JSON.parse(ajax.responseText);
// // console.log('custom uptoken_func:' + res.uptoken);
// // return res.uptoken;
// // } else {
// // console.log('custom uptoken_func err');
// // return '';
// // }
// // },
// domain: $('#domain').val(),
// get_new_uptoken: true,
// // downtoken_url: '/downtoken',
// // unique_names: true,
// // save_key: true,
// // x_vars: {
// // 'id': '1234',
// // 'time': function(up, file) {
// // var time = (new Date()).getTime();
// // // do something with 'time'
// // return time;
// // },
// // },
// auto_start: true,
// log_level: 5,
// init: {
// 'FilesAdded': function(up, files) {
// $('table').show();
// $('#upload_box').show();
// $('#success').hide();
// $('#info_box').hide();
// $.cookie('path', decodeURI(getCookieByString("path_tmp")));
// plupload.each(files, function(file) {
// var progress = new FileProgress(file, 'fsUploadProgress');
// progress.setStatus("等待...");
// progress.bindUploadCancel(up);
// });
// },
// 'BeforeUpload': function(up, file) {
// var progress = new FileProgress(file, 'fsUploadProgress');
// var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
// if (up.runtime === 'html5' && chunk_size) {
// progress.setChunkProgess(chunk_size);
// }
// },
// 'UploadProgress': function(up, file) {
// var progress = new FileProgress(file, 'fsUploadProgress');
// var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
// progress.setProgress(file.percent + "%", file.speed, chunk_size);
// },
// 'UploadComplete': function(up, file) {
// $('#success').show();
// toastr["success"]("队列全部文件处理完毕");
// getMemory();
// },
// 'FileUploaded': function(up, file, info) {
// var progress = new FileProgress(file, 'fsUploadProgress');
// progress.setComplete(up, info);
// },
// 'Error': function(up, err, errTip) {
// $('#upload_box').show();
// $('table').show();
// $('#info_box').hide();
// var progress = new FileProgress(err.file, 'fsUploadProgress');
// progress.setError();
// progress.setStatus(errTip);
// toastr["error"]("上传时遇到错误");
// }
// // ,
// // 'Key': function(up, file) {
// // var key = "";
// // // do something with key
// // return key
// // }
// }
// });
// uploader.bind('FileUploaded', function(up,file) {
// console.log('a file is uploaded');
// });
// $('#container').on(
// 'dragenter',
// function(e) {
// e.preventDefault();
// $('#container').addClass('draging');
// e.stopPropagation();
// }
// ).on('drop', function(e) {
// e.preventDefault();
// $('#container').removeClass('draging');
// e.stopPropagation();
// }).on('dragleave', function(e) {
// e.preventDefault();
// $('#container').removeClass('draging');
// e.stopPropagation();
// }).on('dragover', function(e) {
// e.preventDefault();
// $('#container').addClass('draging');
// e.stopPropagation();
// });
// $('#show_code').on('click', function() {
// $('#myModal-code').modal();
// $('pre code').each(function(i, e) {
// hljs.highlightBlock(e);
// });
// });
// $('body').on('click', 'table button.btn', function() {
// $(this).parents('tr').next().toggle();
// });
// var getRotate = function(url) {
// if (!url) {
// return 0;
// }
// var arr = url.split('/');
// for (var i = 0, len = arr.length; i < len; i++) {
// if (arr[i] === 'rotate') {
// return parseInt(arr[i + 1], 10);
// }
// }
// return 0;
// };
// $('#myModal-img .modal-body-footer').find('a').on('click', function() {
// var img = $('#myModal-img').find('.modal-body img');
// var key = img.data('key');
// var oldUrl = img.attr('src');
// var originHeight = parseInt(img.data('h'), 10);
// var fopArr = [];
// var rotate = getRotate(oldUrl);
// if (!$(this).hasClass('no-disable-click')) {
// $(this).addClass('disabled').siblings().removeClass('disabled');
// if ($(this).data('imagemogr') !== 'no-rotate') {
// fopArr.push({
// 'fop': 'imageMogr2',
// 'auto-orient': true,
// 'strip': true,
// 'rotate': rotate,
// 'format': 'png'
// });
// }
// } else {
// $(this).siblings().removeClass('disabled');
// var imageMogr = $(this).data('imagemogr');
// if (imageMogr === 'left') {
// rotate = rotate - 90 < 0 ? rotate + 270 : rotate - 90;
// } else if (imageMogr === 'right') {
// rotate = rotate + 90 > 360 ? rotate - 270 : rotate + 90;
// }
// fopArr.push({
// 'fop': 'imageMogr2',
// 'auto-orient': true,
// 'strip': true,
// 'rotate': rotate,
// 'format': 'png'
// });
// }
// $('#myModal-img .modal-body-footer').find('a.disabled').each(function() {
// var watermark = $(this).data('watermark');
// var imageView = $(this).data('imageview');
// var imageMogr = $(this).data('imagemogr');
// if (watermark) {
// fopArr.push({
// fop: 'watermark',
// mode: 1,
// image: 'http://www.b1.qiniudn.com/images/logo-2.png',
// dissolve: 100,
// gravity: watermark,
// dx: 100,
// dy: 100
// });
// }
// if (imageView) {
// var height;
// switch (imageView) {
// case 'large':
// height = originHeight;
// break;
// case 'middle':
// height = originHeight * 0.5;
// break;
// case 'small':
// height = originHeight * 0.1;
// break;
// default:
// height = originHeight;
// break;
// }
// fopArr.push({
// fop: 'imageView2',
// mode: 3,
// h: parseInt(height, 10),
// q: 100,
// format: 'png'
// });
// }
// if (imageMogr === 'no-rotate') {
// fopArr.push({
// 'fop': 'imageMogr2',
// 'auto-orient': true,
// 'strip': true,
// 'rotate': 0,
// 'format': 'png'
// });
// }
// });
// var newUrl = Qiniu.pipeline(fopArr, key);
// var newImg = new Image();
// img.attr('src', 'images/loading.gif');
// newImg.onload = function() {
// img.attr('src', newUrl);
// img.parent('a').attr('href', newUrl);
// };
// newImg.src = newUrl;
// return false;
// });
// function t(){
// uploader.getNewUpToken();
// }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,323 +0,0 @@
/*global plupload */
/*global qiniu */
function FileProgress(file, targetID) {
this.fileProgressID = file.id;
this.file = file;
this.opacity = 100;
this.height = 0;
this.fileProgressWrapper = $("#" + this.fileProgressID);
if (!this.fileProgressWrapper.length) {
// <div class="progress">
// <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%">
// <span class="sr-only">20% Complete</span>
// </div>
// </div>
this.fileProgressWrapper = $("<tr></tr>");
var Wrappeer = this.fileProgressWrapper;
Wrappeer.attr("id", this.fileProgressID).addClass("progressContainer");
var progressText = $("<td/>");
progressText.addClass("progressName").text(file.name);
var fileSize = plupload.formatSize(file.size).toUpperCase();
var progressSize = $("<td/>");
progressSize.addClass("progressFileSize").text(fileSize);
var progressBarTd = $("<td/>");
var progressBarBox = $("<div/>");
progressBarBox.addClass("info");
var progressBarWrapper = $("<div/>");
progressBarWrapper.addClass("progress progress-striped");
var progressBar = $("<div/>");
progressBar
.addClass("progress-bar progress-bar-info")
.attr("role", "progressbar")
.attr("aria-valuemax", 100)
.attr("aria-valuenow", 0)
.attr("aria-valuein", 0)
.width("0%");
var progressBarPercent = $("<span class=sr-only />");
progressBarPercent.text(fileSize);
var progressCancel = $("<a href=javascript:; />");
progressCancel.show().addClass("progressCancel").text("×");
progressBar.append(progressBarPercent);
progressBarWrapper.append(progressBar);
progressBarBox.append(progressBarWrapper);
progressText.append(progressCancel);
var progressBarStatus = $('<div class="status text-center"/>');
progressBarBox.append(progressBarStatus);
progressBarTd.append(progressBarBox);
Wrappeer.append(progressText);
Wrappeer.append(progressSize);
Wrappeer.append(progressBarTd);
$("#" + targetID).append(Wrappeer);
} else {
this.reset();
}
this.height = this.fileProgressWrapper.offset().top;
this.setTimer(null);
}
FileProgress.prototype.setTimer = function (timer) {
this.fileProgressWrapper.FP_TIMER = timer;
};
FileProgress.prototype.getTimer = function (timer) {
return this.fileProgressWrapper.FP_TIMER || null;
};
FileProgress.prototype.reset = function () {
this.fileProgressWrapper.attr("class", "progressContainer");
this.fileProgressWrapper
.find("td .progress .progress-bar-info")
.attr("aria-valuenow", 0)
.width("0%")
.find("span")
.text("");
this.appear();
};
FileProgress.prototype.setChunkProgess = function (chunk_size) {
var chunk_amount = Math.ceil(this.file.size / chunk_size);
if (chunk_amount === 1) {
return false;
}
var viewProgess = $(
'<button class="btn btn-default">查看分块上传进度</button>'
);
var progressBarChunkTr = $(
'<tr class="chunk-status-tr"><td colspan=3></td></tr>'
);
var progressBarChunk = $("<div/>");
for (var i = 1; i <= chunk_amount; i++) {
var col = $('<div class="col-md-2"/>');
var progressBarWrapper = $(
'<div class="progress progress-striped"></div'
);
var progressBar = $("<div/>");
progressBar
.addClass("progress-bar progress-bar-info text-left")
.attr("role", "progressbar")
.attr("aria-valuemax", 100)
.attr("aria-valuenow", 0)
.attr("aria-valuein", 0)
.width("0%")
.attr("id", this.file.id + "_" + i)
.text("");
var progressBarStatus = $("<span/>");
progressBarStatus.addClass("chunk-status").text();
progressBarWrapper.append(progressBar);
progressBarWrapper.append(progressBarStatus);
col.append(progressBarWrapper);
progressBarChunk.append(col);
}
if (!this.fileProgressWrapper.find("td:eq(2) .btn-default").length) {
this.fileProgressWrapper.find("td>div").append(viewProgess);
}
progressBarChunkTr.hide().find("td").append(progressBarChunk);
progressBarChunkTr.insertAfter(this.fileProgressWrapper);
};
FileProgress.prototype.setProgress = function (percentage, speed, chunk_size) {
this.fileProgressWrapper.attr("class", "progressContainer green");
var file = this.file;
var uploaded = file.loaded;
var size = plupload.formatSize(uploaded).toUpperCase();
var formatSpeed = plupload.formatSize(speed).toUpperCase();
var progressbar = this.fileProgressWrapper
.find("td .progress")
.find(".progress-bar-info");
if (this.fileProgressWrapper.find(".status").text() === "取消上传") {
return;
}
this.fileProgressWrapper
.find(".status")
.text("已上传: " + size + " 上传速度: " + formatSpeed + "/s");
percentage = parseInt(percentage, 10);
if (file.status !== plupload.DONE && percentage === 100) {
percentage = 99;
}
progressbar
.attr("aria-valuenow", percentage)
.css("width", percentage + "%");
if (chunk_size) {
var chunk_amount = Math.ceil(file.size / chunk_size);
if (chunk_amount === 1) {
return false;
}
var current_uploading_chunk = Math.ceil(uploaded / chunk_size);
var pre_chunk, text;
for (var index = 0; index < current_uploading_chunk; index++) {
pre_chunk = $("#" + file.id + "_" + index);
pre_chunk
.width("100%")
.removeClass()
.addClass("alert alert-success")
.attr("aria-valuenow", 100);
text = "块" + index + "上传进度100%";
pre_chunk.next().html(text);
}
var currentProgessBar = $(
"#" + file.id + "_" + current_uploading_chunk
);
var current_chunk_percent;
if (current_uploading_chunk < chunk_amount) {
if (uploaded % chunk_size) {
current_chunk_percent = (
((uploaded % chunk_size) / chunk_size) *
100
).toFixed(2);
} else {
current_chunk_percent = 100;
currentProgessBar.removeClass().addClass("alert alert-success");
}
} else {
var last_chunk_size = file.size - chunk_size * (chunk_amount - 1);
var left_file_size = file.size - uploaded;
if (left_file_size % last_chunk_size) {
current_chunk_percent = (
((uploaded % chunk_size) / last_chunk_size) *
100
).toFixed(2);
} else {
current_chunk_percent = 100;
currentProgessBar.removeClass().addClass("alert alert-success");
}
}
currentProgessBar.width(current_chunk_percent + "%");
currentProgessBar.attr("aria-valuenow", current_chunk_percent);
text =
"块" +
current_uploading_chunk +
"上传进度" +
current_chunk_percent +
"%";
currentProgessBar.next().html(text);
}
this.appear();
};
FileProgress.prototype.setComplete = function (up, info) {
var td = this.fileProgressWrapper.find("td:eq(2)"),
tdProgress = td.find(".progress");
var res;
var url;
if (uploadConfig.saveType == "oss") {
url = "oss";
str = "<div class='success_text'>上传成功</div>";
} else {
res = $.parseJSON(info);
if (res.url) {
url = res.url;
str = "<div class='success_text'>上传成功</div>";
} else {
var domain = up.getOption("domain");
url = domain + encodeURI(res.key);
var link = domain + res.key;
str = "<div class='success_text'>上传成功</div>";
}
}
tdProgress.html(str).removeClass().next().next(".status").hide();
this.fileProgressWrapper.find("td:eq(0) .progressCancel").hide();
td.find(".status").hide();
angular
.element(document.querySelector("angular-filemanager > div"))
.scope()
.fileNavigator.refresh();
};
FileProgress.prototype.setError = function () {
this.fileProgressWrapper.find("td:eq(2)").attr("class", "text-warning");
this.fileProgressWrapper.find("td:eq(2) .progress").css("width", 0).hide();
this.fileProgressWrapper.find("button").hide();
this.fileProgressWrapper.next(".chunk-status-tr").hide();
};
FileProgress.prototype.setCancelled = function (manual) {
var progressContainer = "progressContainer";
if (!manual) {
progressContainer += " red";
}
this.fileProgressWrapper.attr("class", progressContainer);
this.fileProgressWrapper.find("td .progress").remove();
this.fileProgressWrapper.find("td:eq(2) .btn-default").hide();
this.fileProgressWrapper.find("td:eq(0) .progressCancel").hide();
};
FileProgress.prototype.setStatus = function (status, isUploading) {
if (!isUploading) {
this.fileProgressWrapper
.find(".status")
.text(status)
.attr("class", "status text-left");
}
};
// 绑定取消上传事件
FileProgress.prototype.bindUploadCancel = function (up) {
var self = this;
if (up) {
self.fileProgressWrapper
.find("td:eq(0) .progressCancel")
.on("click", function () {
self.setCancelled(false);
self.setStatus("取消上传");
self.fileProgressWrapper.find(".status").css("left", "0");
up.removeFile(self.file);
});
}
};
FileProgress.prototype.appear = function () {
if (this.getTimer() !== null) {
clearTimeout(this.getTimer());
this.setTimer(null);
}
if (this.fileProgressWrapper[0].filters) {
try {
this.fileProgressWrapper[0].filters.item(
"DXImageTransform.Microsoft.Alpha"
).opacity = 100;
} catch (e) {
// If it is not set initially, the browser will throw an error. This will set it if it is not set yet.
this.fileProgressWrapper.css(
"filter",
"progid:DXImageTransform.Microsoft.Alpha(opacity=100)"
);
}
} else {
this.fileProgressWrapper.css("opacity", 1);
}
this.fileProgressWrapper.css("height", "");
this.height = this.fileProgressWrapper.offset().top;
this.opacity = 100;
this.fileProgressWrapper.show();
};

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -57,6 +57,10 @@ import {
toggleSnackbar,
} from "../../redux/explorer";
import { pathJoin } from "../Uploader/core/utils";
import {
openFileSelector,
openFolderSelector,
} from "../../redux/viewUpdate/action";
const styles = () => ({
propover: {},
@ -159,6 +163,12 @@ const mapDispatchToProps = (dispatch) => {
startBatchDownload: (share) => {
dispatch(startBatchDownload(share));
},
openFileSelector: () => {
dispatch(openFileSelector());
},
openFolderSelector: () => {
dispatch(openFolderSelector());
},
};
};
@ -202,21 +212,6 @@ class ContextMenuCompoment extends Component {
);
};
clickUpload = (id) => {
this.props.changeContextMenu("empty", false);
const uploadButton = document.getElementsByClassName(id)[0];
if (document.body.contains(uploadButton)) {
uploadButton.click();
} else {
this.props.toggleSnackbar(
"top",
"right",
"上传组件还未加载完成",
"warning"
);
}
};
// 暂时只对空白处右键菜单使用这个函数疑似有bug会导致的一个菜单被默认选中。
// 相关issue https://github.com/mui-org/material-ui/issues/23747
renderMenuItems = (items) => {
@ -272,13 +267,13 @@ class ContextMenuCompoment extends Component {
center: [
{
condition: true,
onClick: () => this.clickUpload("uploadFileForm"),
onClick: () => this.props.openFileSelector(),
icon: <UploadIcon />,
text: "上传文件",
},
{
condition: true,
onClick: () => this.clickUpload("uploadFolderForm"),
onClick: () => this.props.openFolderSelector(),
icon: <FolderUpload />,
text: "上传目录",
},
@ -344,9 +339,7 @@ class ContextMenuCompoment extends Component {
<Divider className={classes.divider} />
<MenuItem
dense
onClick={() =>
this.clickUpload("uploadFileForm")
}
onClick={() => this.props.openFileSelector()}
>
<StyledListItemIcon>
<UploadIcon />
@ -357,9 +350,7 @@ class ContextMenuCompoment extends Component {
</MenuItem>
<MenuItem
dense
onClick={() =>
this.clickUpload("uploadFolderForm")
}
onClick={() => this.props.openFolderSelector()}
>
<StyledListItemIcon>
<FolderUpload />

View File

@ -1,392 +0,0 @@
import React, { Component } from "react";
import CloseIcon from "@material-ui/icons/Close";
import AddIcon from "@material-ui/icons/AddCircleOutline";
import DeleteIcon from "@material-ui/icons/Delete";
import RefreshIcon from "@material-ui/icons/Refresh";
import { isWidthDown } from "@material-ui/core/withWidth";
import { darken, lighten } from "@material-ui/core/styles/colorManipulator";
import {
withStyles,
Dialog,
ListItemText,
ListItem,
List,
Divider,
AppBar,
Toolbar,
IconButton,
Typography,
Slide,
ListItemSecondaryAction,
withWidth,
DialogContent,
Tooltip,
} from "@material-ui/core";
import TypeIcon from "../FileManager/TypeIcon";
import { withTheme } from "@material-ui/core/styles";
const styles = (theme) => ({
appBar: {
position: "relative",
},
flex: {
flex: 1,
},
progressBar: {
marginTop: 5,
},
minHight: {
[theme.breakpoints.up("sm")]: {
minWidth: 500,
},
padding: 0,
},
dialogContent: {
padding: 0,
},
successStatus: {
color: "#4caf50",
},
errorStatus: {
color: "#ff5722",
wordBreak: "break-all",
},
listAction: {
marginLeft: 20,
marginRight: 20,
},
delete: {
zIndex: 9,
},
progressContainer: {
position: "relative",
},
progressContent: {
position: "relative",
zIndex: 9,
},
progress: {
transition: "width .4s linear",
zIndex: 1,
height: "100%",
position: "absolute",
left: 0,
top: 0,
},
fileName: {
wordBreak: "break-all",
},
});
class FileList extends Component {
state = {
open: false,
files: [],
};
//入队
enQueue(files) {
this.setState({
files: [...this.state.files, ...files],
});
}
deQueue(file) {
const filesNow = [...this.state.files];
const fileID = filesNow.findIndex((f) => {
return f.id === file.id;
});
if (fileID !== -1) {
filesNow.splice(fileID, 1);
this.setState({
files: filesNow,
open: filesNow.length !== 0,
});
}
}
updateStatus(file) {
const filesNow = [...this.state.files];
const fileID = filesNow.findIndex((f) => {
return f.id === file.id;
});
if (!file.errMsg || file.ignoreMsg) {
if (filesNow[fileID] && !filesNow[fileID].errMsg) {
filesNow[fileID] = file;
this.setState({
files: filesNow,
});
}
} else {
file.ignoreMsg = true;
}
}
setComplete(file) {
const filesNow = [...this.state.files];
const fileID = filesNow.findIndex((f) => {
return f.id === file.id;
});
if (fileID !== -1) {
if (filesNow[fileID].status !== 4) {
filesNow[fileID].status = 5;
this.setState({
files: filesNow,
});
}
}
}
setError(file, errMsg) {
const filesNow = [...this.state.files];
const fileID = filesNow.findIndex((f) => {
return f.id === file.id;
});
if (fileID !== -1) {
filesNow[fileID].status = 4;
filesNow[fileID].errMsg = errMsg;
} else {
file.status = 4;
file.errMsg = errMsg;
filesNow.push(file);
}
this.setState({
files: filesNow,
});
}
Transition(props) {
return <Slide direction="up" {...props} />;
}
openFileList = () => {
if (!this.state.open) {
this.setState({ open: true });
}
};
cancelUpload = (file) => {
this.props.cancelUpload(file);
// this.deQueue(file);
};
handleClose = () => {
this.setState({ open: false });
};
addNewFile = () => {
document.getElementsByClassName("uploadFileForm")[0].click();
};
getProgressBackground = () => {
return this.props.theme.palette.type === "light"
? lighten(this.props.theme.palette.primary.main, 0.8)
: darken(this.props.theme.palette.background.paper, 0.2);
};
render() {
const { classes } = this.props;
const { width } = this.props;
this.props.inRef({
openFileList: this.openFileList.bind(this),
enQueue: this.enQueue.bind(this),
updateStatus: this.updateStatus.bind(this),
setComplete: this.setComplete.bind(this),
setError: this.setError.bind(this),
});
return (
<Dialog
fullScreen={isWidthDown("sm", width)}
open={this.state.open}
onClose={this.handleClose}
TransitionComponent={this.Transition}
>
<AppBar className={classes.appBar}>
<Toolbar>
<IconButton
color="inherit"
onClick={this.handleClose}
aria-label="Close"
>
<CloseIcon />
</IconButton>
<Typography
variant="h6"
color="inherit"
className={classes.flex}
>
上传队列
</Typography>
<IconButton color="inherit" onClick={this.addNewFile}>
<AddIcon />
</IconButton>
</Toolbar>
</AppBar>
<DialogContent className={classes.dialogContent}>
<List className={classes.minHight}>
{this.state.files.map((item, i) => (
<div key={i} className={classes.progressContainer}>
{item.status === 2 && (
<div
style={{
backgroundColor: this.getProgressBackground(),
width: item.percent + "%",
}}
className={classes.progress}
/>
)}
<ListItem
className={classes.progressContent}
button
>
<TypeIcon fileName={item.name} isUpload />
{item.status === 1 && (
<ListItemText
className={classes.listAction}
primary={
<span
className={classes.fileName}
>
{item.name}
</span>
}
secondary={<div>排队中...</div>}
/>
)}
{item.status === 2 && (
<ListItemText
className={classes.listAction}
primary={
<span
className={classes.fileName}
>
{item.name}
</span>
}
secondary={
<div>
{item.percent <= 99 && (
<>
{window.plupload
.formatSize(
item.speed
)
.toUpperCase()}
/s {" "}
{window.plupload
.formatSize(
item.loaded
)
.toUpperCase()}{" "}
, {" "}
{window.plupload
.formatSize(
item.size
)
.toUpperCase()}{" "}
- {item.percent}%{" "}
</>
)}
{item.percent > 99 && (
<div>处理中...</div>
)}
</div>
}
/>
)}
{item.status === 3 && (
<ListItemText
className={classes.listAction}
primary={
<span
className={classes.fileName}
>
{item.name}
</span>
}
secondary={item.status}
/>
)}
{item.status === 4 && (
<ListItemText
className={classes.listAction}
primary={
<span
className={classes.fileName}
>
{item.name}
</span>
}
secondary={
<div
className={
classes.errorStatus
}
>
{item.errMsg}
<br />
</div>
}
/>
)}
{item.status === 5 && (
<ListItemText
className={classes.listAction}
primary={
<span
className={classes.fileName}
>
{item.name}
</span>
}
secondary={
<div
className={
classes.successStatus
}
>
已完成
<br />
</div>
}
/>
)}
<ListItemSecondaryAction
className={classes.delete}
>
{item.status !== 4 && (
<IconButton
aria-label="Delete"
onClick={() =>
this.cancelUpload(item)
}
>
<DeleteIcon />
</IconButton>
)}
{item.status === 4 && (
<Tooltip title={"重试"}>
<IconButton
aria-label="Delete"
onClick={() =>
this.reQueue(item)
}
>
<RefreshIcon />
</IconButton>
</Tooltip>
)}
</ListItemSecondaryAction>
</ListItem>
<Divider />
</div>
))}
</List>
</DialogContent>
</Dialog>
);
}
}
FileList.propTypes = {};
export default withStyles(styles)(withWidth()(withTheme(FileList)));

View File

@ -1,234 +0,0 @@
import React, { Component } from "react";
import uploaderLoader from "../../loader";
import { connect } from "react-redux";
import FileList from "./FileList.js";
import Auth from "../../middleware/Auth";
import UploadButton from "../Dial/Create.js";
import { basename, pathJoin } from "../../utils";
import { refreshFileList, refreshStorage, toggleSnackbar } from "../../redux/explorer";
let loaded = false;
const mapStateToProps = (state) => {
return {
path: state.navigator.path,
keywords: state.explorer.keywords,
};
};
const mapDispatchToProps = (dispatch) => {
return {
refreshFileList: () => {
dispatch(refreshFileList());
},
refreshStorage: () => {
dispatch(refreshStorage());
},
toggleSnackbar: (vertical, horizontal, msg, color) => {
dispatch(toggleSnackbar(vertical, horizontal, msg, color));
},
};
};
class UploaderComponent extends Component {
constructor(props) {
super(props);
this.state = {
queued: 0,
};
}
setRef(val) {
window.fileList = val;
}
cancelUpload(file) {
this.uploader.removeFile(file);
}
reQueue = (file) => {
this.uploader.addFile(file.getSource());
this.props.toggleSnackbar(
"top",
"right",
"文件已经重新加入上传队列",
"info"
);
};
getChunkSize(policyType) {
if (policyType === "qiniu") {
return 4 * 1024 * 1024;
}
if (policyType === "onedrive") {
return 100 * 1024 * 1024;
}
return 0;
}
fileAdd = (up, files) => {
const path = window.currntPath ? window.currntPath : this.props.path;
if (
this.props.keywords === "" &&
window.location.pathname.toLowerCase().startsWith("/home")
) {
window.fileList["openFileList"]();
const enqueFiles = files
// 不上传Mac下的布局文件 .DS_Store
.filter((file) => {
const isDsStore = file.name.toLowerCase() === ".ds_store";
if (isDsStore) {
up.removeFile(file);
}
return !isDsStore;
})
.map((file) => {
const source = file.getSource();
if (source.relativePath && source.relativePath !== "") {
file.path = basename(
pathJoin([path, source.relativePath])
);
window.pathCache[file.id] = basename(
pathJoin([path, source.relativePath])
);
} else {
window.pathCache[file.id] = path;
file.path = path;
}
return file;
});
window.fileList["enQueue"](enqueFiles);
} else {
window.plupload.each(files, (files) => {
up.removeFile(files);
});
}
};
UNSAFE_componentWillReceiveProps({ isScriptLoaded, isScriptLoadSucceed }) {
if (isScriptLoaded && !this.props.isScriptLoaded) {
// load finished
if (isScriptLoadSucceed) {
if (loaded) {
return;
}
loaded = true;
const user = Auth.GetUser();
this.uploader = window.Qiniu.uploader({
runtimes: "html5",
browse_button: ["pickfiles", "pickfolder"],
container: "container",
drop_element: "container",
max_file_size:
user.policy.maxSize === "0.00mb"
? 0
: user.policy.maxSize,
dragdrop: true,
chunk_size: this.getChunkSize(user.policy.saveType),
filters: {
mime_types:
user.policy.allowedType === null ||
user.policy.allowedType.length === 0
? []
: [
{
title: "files",
extensions: user.policy.allowedType.join(
","
),
},
],
},
// iOS不能多选
multi_selection: true,
uptoken_url: "/api/v3/file/upload/credential",
uptoken: user.policy.saveType === "local" ? "token" : null,
domain: "s",
max_retries: 0,
get_new_uptoken: true,
auto_start: true,
log_level: 5,
init: {
FilesAdded: this.fileAdd,
// eslint-disable-next-line @typescript-eslint/no-empty-function
BeforeUpload: function () {},
QueueChanged: (up) => {
this.setState({ queued: up.total.queued });
},
UploadProgress: (up, file) => {
window.fileList["updateStatus"](file);
},
UploadComplete: (up, file) => {
if (file.length === 0) {
return;
}
console.log(
"UploadComplete",
file[0].status,
file[0]
);
for (let i = 0; i < file.length; i++) {
if (file[i].status === 5) {
window.fileList["setComplete"](file[i]);
}
}
// 无异步操作的策略,直接刷新
if (
user.policy.saveType !== "onedrive" &&
user.policy.saveType !== "cos"
) {
this.props.refreshFileList();
this.props.refreshStorage();
}
},
Fresh: () => {
this.props.refreshFileList();
this.props.refreshStorage();
},
// eslint-disable-next-line @typescript-eslint/no-empty-function
FileUploaded: function () {},
Error: (up, err, errTip) => {
window.fileList["openFileList"]();
window.fileList["setError"](err.file, errTip);
},
// eslint-disable-next-line @typescript-eslint/no-empty-function
FilesRemoved: () => {},
},
});
// this.fileList["openFileList"]();
} else this.onError();
}
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
onError() {}
openFileList = () => {
window.fileList["openFileList"]();
};
render() {
return (
<div>
<FileList
inRef={this.setRef.bind(this)}
cancelUpload={this.cancelUpload.bind(this)}
reQueue={this.reQueue.bind(this)}
/>
{this.props.keywords === "" && (
<UploadButton
Queued={this.state.queued}
openFileList={this.openFileList}
/>
)}
</div>
);
}
}
const Uploader = connect(mapStateToProps, mapDispatchToProps, null, {
forwardRef: true,
})(uploaderLoader()(UploaderComponent));
export default Uploader;

View File

@ -33,6 +33,12 @@ export default function Uploader() {
const policy = useSelector((state) => state.explorer.currentPolicy);
const isLogin = useSelector((state) => state.viewUpdate.isLogin);
const path = useSelector((state) => state.navigator.path);
const fileSelectCounter = useSelector(
(state) => state.viewUpdate.openFileSelector
);
const folderSelectCounter = useSelector(
(state) => state.viewUpdate.openFolderSelector
);
const location = useLocation();
const dispatch = useDispatch();
const ToggleSnackbar = useCallback(
@ -192,6 +198,18 @@ export default function Uploader() {
});
};
useEffect(() => {
if (fileSelectCounter > 0) {
selectFile(path);
}
}, [fileSelectCounter]);
useEffect(() => {
if (folderSelectCounter > 0) {
selectFile(path, SelectType.Directory);
}
}, [folderSelectCounter]);
const deleteTask = (filter) => {
setUploaders((uploaders) => uploaders.filter(filter));
};

View File

@ -26,9 +26,13 @@ export default class COS extends Base {
protected async afterUpload(): Promise<any> {
this.transit(Status.finishing);
this.logger.info(`Sending COS upload callback...`);
return cosUploadCallback(
this.task.session!.sessionID,
this.cancelToken.token
);
try {
await cosUploadCallback(
this.task.session!.sessionID,
this.cancelToken.token
);
} catch (e) {
this.logger.warn(`Failed to finish COS upload:`, e);
}
}
}

View File

@ -58,6 +58,13 @@ export default function VideoViewer() {
return () => {
if (playing && document.pictureInPictureEnabled && dp) {
dp.video.requestPictureInPicture();
dp.video.addEventListener(
"leavepictureinpicture",
() => {
dp.video.pause();
},
false
);
}
};
}, []);

View File

@ -1,136 +0,0 @@
import React, { Component } from "react";
import PropTypes from "prop-types";
import hoistStatics from "hoist-non-react-statics";
import { newScript, series, noop } from "./utils";
const loadedScript = [];
const pendingScripts = {};
let failedScript = [];
const addCache = (entry) => {
if (loadedScript.indexOf(entry) < 0) {
loadedScript.push(entry);
}
};
const removeFailedScript = () => {
if (failedScript.length > 0) {
failedScript.forEach((script) => {
const node = document.querySelector(`script[src='${script}']`);
if (node != null) {
node.parentNode.removeChild(node);
}
});
failedScript = [];
}
};
export function startLoadingScripts(scripts, onComplete = noop) {
// sequence load
const loadNewScript = (script) => {
const src = typeof script === "object" ? script.src : script;
if (loadedScript.indexOf(src) < 0) {
return (taskComplete) => {
const callbacks = pendingScripts[src] || [];
callbacks.push(taskComplete);
pendingScripts[src] = callbacks;
if (callbacks.length === 1) {
return newScript(script)((err) => {
pendingScripts[src].forEach((cb) => cb(err, src));
delete pendingScripts[src];
});
}
};
}
};
const tasks = scripts.map((src) => {
if (Array.isArray(src)) {
return src.map(loadNewScript);
} else return loadNewScript(src);
});
series(...tasks)((err, src) => {
if (err) {
failedScript.push(src);
} else {
if (Array.isArray(src)) {
src.forEach(addCache);
} else addCache(src);
}
})((err) => {
removeFailedScript();
onComplete(err);
});
}
const uploaderLoader = () => (WrappedComponent) => {
class ScriptLoader extends Component {
static propTypes = {
onScriptLoaded: PropTypes.func,
};
static defaultProps = {
onScriptLoaded: noop,
};
constructor(props, context) {
super(props, context);
this.state = {
isScriptLoaded: false,
isScriptLoadSucceed: false,
};
this._isMounted = false;
}
componentDidMount() {
this._isMounted = true;
const scripts = [
["/static/js/uploader/moxie.js"],
["/static/js/uploader/plupload.dev.js"],
["/static/js/uploader/i18n/zh_CN.js"],
["/static/js/uploader/ui.js"],
["/static/js/uploader/uploader_" + window.policyType + ".js"],
];
startLoadingScripts(scripts, (err) => {
if (this._isMounted) {
this.setState(
{
isScriptLoaded: true,
isScriptLoadSucceed: !err,
},
() => {
if (!err) {
this.props.onScriptLoaded();
}
}
);
}
});
}
componentWillUnmount() {
this._isMounted = false;
}
// getWrappedInstance() {
// return this.refs.wrappedInstance;
// }
render() {
const props = {
...this.props,
...this.state,
ref: "wrappedInstance",
};
return <WrappedComponent {...props} />;
}
}
return hoistStatics(ScriptLoader, WrappedComponent);
};
export default uploaderLoader;

View File

@ -1,109 +0,0 @@
export const isDefined = (val) => val != null;
export const isFunction = (val) => typeof val === "function";
// eslint-disable-next-line @typescript-eslint/no-empty-function
export const noop = () => {};
export const newScript = (src) => (cb) => {
const scriptElem = document.createElement("script");
if (typeof src === "object") {
// copy every property to the element
for (const key in src) {
if (Object.prototype.hasOwnProperty.call(src, key)) {
scriptElem[key] = src[key];
}
}
src = src.src;
} else {
scriptElem.src = src;
}
scriptElem.addEventListener("load", () => cb(null, src));
scriptElem.addEventListener("error", () => cb(true, src));
document.body.appendChild(scriptElem);
return scriptElem;
};
const keyIterator = (cols) => {
const keys = Object.keys(cols);
let i = -1;
return {
next() {
i++; // inc
if (i >= keys.length) return null;
else return keys[i];
},
};
};
// tasks should be a collection of thunk
export const parallel = (...tasks) => (each) => (cb) => {
let hasError = false;
let successed = 0;
const ret = [];
tasks = tasks.filter(isFunction);
if (tasks.length <= 0) cb(null);
else {
tasks.forEach((task, i) => {
const thunk = task;
thunk((err, ...args) => {
if (err) hasError = true;
else {
// collect result
if (args.length <= 1) args = args[0];
ret[i] = args;
successed++;
}
if (isFunction(each)) each.call(null, err, args, i);
if (hasError) cb(true);
else if (tasks.length === successed) {
cb(null, ret);
}
});
});
}
};
// tasks should be a collection of thunk
export const series = (...tasks) => (each) => (cb) => {
tasks = tasks.filter((val) => val != null);
const nextKey = keyIterator(tasks);
const nextThunk = () => {
const key = nextKey.next();
let thunk = tasks[key];
// eslint-disable-next-line prefer-spread
if (Array.isArray(thunk))
// eslint-disable-next-line prefer-spread
thunk = parallel.apply(null, thunk).call(null, each);
return [+key, thunk]; // convert `key` to number
};
let key, thunk;
let next = nextThunk();
key = next[0];
thunk = next[1];
if (thunk == null) return cb(null);
const ret = [];
const iterator = () => {
thunk((err, ...args) => {
if (args.length <= 1) args = args[0];
if (isFunction(each)) each.call(null, err, args, key);
if (err) cb(err);
else {
// collect result
ret.push(args);
next = nextThunk();
key = next[0];
thunk = next[1];
if (thunk == null) return cb(null, ret);
// finished
else iterator();
}
});
};
iterator();
};

View File

@ -46,3 +46,15 @@ export const setOptionModal = (option: any) => {
option: option,
};
};
export const openFileSelector = () => {
return {
type: "OPEN_FILE_SELECTOR",
};
};
export const openFolderSelector = () => {
return {
type: "OPEN_FOLDER_SELECTOR",
};
};

View File

@ -59,6 +59,8 @@ export interface ViewUpdateState {
msg: string;
color: string;
};
openFileSelector: number;
openFolderSelector: number;
}
export const initState: ViewUpdateState = {
// 是否登录
@ -102,6 +104,8 @@ export const initState: ViewUpdateState = {
msg: "",
color: "",
},
openFileSelector: 0,
openFolderSelector: 0,
};
const viewUpdate = (state: ViewUpdateState = initState, action: AnyAction) => {
switch (action.type) {
@ -322,6 +326,18 @@ const viewUpdate = (state: ViewUpdateState = initState, action: AnyAction) => {
}),
contextOpen: false,
});
case "OPEN_FILE_SELECTOR":
return {
...state,
openFileSelector: state.openFileSelector + 1,
contextOpen: false,
};
case "OPEN_FOLDER_SELECTOR":
return {
...state,
openFolderSelector: state.openFolderSelector + 1,
contextOpen: false,
};
default:
return state;
}