pull/1238/head
gedoor 3 years ago
parent 52aafdafc1
commit 9906247ba7
  1. 170
      app/src/main/assets/web/uploadBook/js/common.js
  2. 114
      app/src/main/assets/web/uploadBook/js/html5_fun.js
  3. 93
      app/src/main/assets/web/uploadBook/js/langSwich.js
  4. 101
      app/src/main/assets/web/uploadBook/js/swf_fun.js
  5. 9
      app/src/main/java/io/legado/app/api/controller/BookController.kt
  6. 11
      app/src/main/java/io/legado/app/web/HttpServer.kt

@ -4,16 +4,16 @@
//全局的配置文件 //全局的配置文件
var config = { var config = {
fileTypes : "txt|epub|umd", //允许上传的文件格式 "txt|epub" // |doc|docx|wps|xls|xlsx|et|ppt|pptx|dps fileTypes: "txt|epub|umd", //允许上传的文件格式 "txt|epub" // |doc|docx|wps|xls|xlsx|et|ppt|pptx|dps
//url : "http://"+location.host+"?action=addBook",//"http://localhost/t/post.php",// //url : "http://"+location.host+"?action=addBook",//"http://localhost/t/post.php",//
url: "http://192.168.1.16:1122/addLocalBook", url: "../addLocalBook",
fileLimitSize : 500 * 1024 *1024 fileLimitSize: 500 * 1024 * 1024
} }
var file = { var file = {
"inQueue" : [], //已经在队列里面的文件,包括 HTML5上传和 Flash上传的 "inQueue": [], //已经在队列里面的文件,包括 HTML5上传和 Flash上传的
"clientHaveFiles" : [] // 客户端已经存在的文件列表 "clientHaveFiles": [] // 客户端已经存在的文件列表
} }
/** /**
@ -23,68 +23,66 @@ var file = {
var filesUpload = []; // var filesUpload = []; //
$.ajax({ $.ajax({
url : "http://"+location.host+'?action=getBooksList&t='+(+new Date()),//"http://localhost/t/t.php",// url: "http://" + location.host + '?action=getBooksList&t=' + (+new Date()),//"http://localhost/t/t.php",//
async:false,//同步获取数据 async: false,//同步获取数据
dataType : "json", dataType: "json",
success:function(data){ success: function (data) {
try{ try {
var dataLen = data.length; var dataLen = data.length;
if(dataLen > 0 ){ if (dataLen > 0) {
for(var i=0; i < dataLen; i++){ for (var i = 0; i < dataLen; i++) {
filesUpload.push(data[i]); filesUpload.push(data[i]);
} }
} }
}catch(e){} } catch (e) { }
} }
}) })
//统计文件大小 //统计文件大小
function countFileSize(fileSize) function countFileSize(fileSize) {
{
var KB = 1024; var KB = 1024;
var MB = 1024 * 1024; var MB = 1024 * 1024;
if(KB >= fileSize){ if (KB >= fileSize) {
return fileSize+"B"; return fileSize + "B";
}else if(MB >= fileSize){ } else if (MB >= fileSize) {
return (fileSize/KB).toFixed(2)+"KB"; return (fileSize / KB).toFixed(2) + "KB";
}else{ } else {
return (fileSize/MB).toFixed(2)+"MB"; return (fileSize / MB).toFixed(2) + "MB";
} }
} }
//如果文件太长进行截取 //如果文件太长进行截取
function substr_string(name) function substr_string(name) {
{
var maxLen = 15; var maxLen = 15;
var len = name.length; var len = name.length;
if(len < 17 )return name; if (len < 17) return name;
var lastIndex = name.lastIndexOf("."); var lastIndex = name.lastIndexOf(".");
var suffix = name.substr(lastIndex); var suffix = name.substr(lastIndex);
var pre = name.substr(0,lastIndex); var pre = name.substr(0, lastIndex);
var preLen = pre.length; var preLen = pre.length;
var preStart = preLen - 10; var preStart = preLen - 10;
//前面10个 + 后面5个 //前面10个 + 后面5个
var fileName = pre.substr(0,10) + "...." + pre.substr( preStart > 4 ? -4 : -preStart , 4)+suffix; var fileName = pre.substr(0, 10) + "...." + pre.substr(preStart > 4 ? -4 : -preStart, 4) + suffix;
return fileName return fileName
} }
function checkFile(file) { function checkFile(file) {
if(file.size > config.fileLimitSize){ if (file.size > config.fileLimitSize) {
return jsonLang.t11; return jsonLang.t11;
} }
if (!file.name || !file.name.toLowerCase().match('('+config.fileTypes+')$')) { if (!file.name || !file.name.toLowerCase().match('(' + config.fileTypes + ')$')) {
return jsonLang.t12; return jsonLang.t12;
} }
var len = filesUpload.length; var len = filesUpload.length;
for(var i=0; i< len; i++){ for (var i = 0; i < len; i++) {
if(filesUpload[i].name == file.name) { if (filesUpload[i].name == file.name) {
return jsonLang.t13; return jsonLang.t13;
} }
} }
@ -101,31 +99,29 @@ function checkFile(file) {
* @param object file 文件对象 * @param object file 文件对象
* @param int type 0 是swf 上传的1 是html5上传的 * @param int type 0 是swf 上传的1 是html5上传的
*/ */
function fileQueued(file, type) function fileQueued(file, type) {
{ var size = 0, fid = file.id, name = "";
var size=0 ,fid=file.id, name="";
type = type || 0; type = type || 0;
if(file != undefined ) if (file != undefined) {
{
//计算文件大小 单位MB //计算文件大小 单位MB
size = countFileSize(file.size); size = countFileSize(file.size);
name = substr_string(file.name) name = substr_string(file.name)
//创建要插入的元素 //创建要插入的元素
// "<tr id='tr_'"+fid+"><td><div class='bh-poStion'><h1>"+name+"</h1>"+ // "<tr id='tr_'"+fid+"><td><div class='bh-poStion'><h1>"+name+"</h1>"+
// "<div class='bh-tip bh-tip3' id='progress_bar_"+fid+"'>"+ // "<div class='bh-tip bh-tip3' id='progress_bar_"+fid+"'>"+
// "<span id='progress_bar_span_"+fid+"'></span></div>"+ // "<span id='progress_bar_span_"+fid+"'></span></div>"+
// "</div></td><td><span class='bh-M'>"+size+"</span></td><td><div class='bh-link' id='handle_button_"+fid+"'>"+ // "</div></td><td><span class='bh-M'>"+size+"</span></td><td><div class='bh-link' id='handle_button_"+fid+"'>"+
// "<a href='javascript:void(0)' onclick=userCancelUpload('"+fid+"',"+type+")>取消</a></div></td></tr>"; // "<a href='javascript:void(0)' onclick=userCancelUpload('"+fid+"',"+type+")>取消</a></div></td></tr>";
var HTML = '<li id="tr_"'+fid+'>'+ var HTML = '<li id="tr_"' + fid + '>' +
'<dl class="grybg">'+ '<dl class="grybg">' +
'<dt>'+name+'</dt>'+ '<dt>' + name + '</dt>' +
'<dd>'+size+'</dd>'+ '<dd>' + size + '</dd>' +
'<dd id="handle_button_'+fid+'" onclick=userCancelUpload("'+fid+'",'+type+') class="orange">'+ '<dd id="handle_button_' + fid + '" onclick=userCancelUpload("' + fid + '",' + type + ') class="orange">' +
'<span id="progress_bar_span_'+fid+'">0%</span> '+jsonLang.t9+'</dd>'+ '<span id="progress_bar_span_' + fid + '">0%</span> ' + jsonLang.t9 + '</dd>' +
'</dl>'+ '</dl>' +
'<div class="jdt"><p id="progress_bar_p_'+fid+'" ></p></div>'+ '<div class="jdt"><p id="progress_bar_p_' + fid + '" ></p></div>' +
'</li>'; '</li>';
@ -137,13 +133,12 @@ function fileQueued(file, type)
} }
} }
function changeTrBackGroundColor() function changeTrBackGroundColor() {
{ var getTr = document.getElementById("tableStyle").getElementsByTagName("dl");
var getTr=document.getElementById("tableStyle").getElementsByTagName("dl"); trNum = getTr.length;
trNum=getTr.length; for (var i = 0; i < trNum; i++) {
for(var i=0;i<trNum;i++){ if (i % 2 == 0) {
if(i%2==0){ getTr[i].style.backgroundColor = "#f3f3f3";
getTr[i].style.backgroundColor="#f3f3f3";
} }
} }
} }
@ -151,40 +146,37 @@ function changeTrBackGroundColor()
//上传时返回的状态 //上传时返回的状态
function uploadProgress(file, bytesLoaded, bytesTotal) function uploadProgress(file, bytesLoaded, bytesTotal) {
{ if (!$("#progress_bar_p_" + file.id).hasClass("orange")) {
if(!$("#progress_bar_p_"+file.id).hasClass("orange")){ $("#progress_bar_p_" + file.id).addClass("orange");
$("#progress_bar_p_"+file.id).addClass("orange");
} }
$("#progress_bar_p_"+file.id).css("width",(bytesLoaded/bytesTotal)*100+"%"); $("#progress_bar_p_" + file.id).css("width", (bytesLoaded / bytesTotal) * 100 + "%");
$("#progress_bar_span_"+file.id).html(parseInt((bytesLoaded/bytesTotal)*100)+"%"); $("#progress_bar_span_" + file.id).html(parseInt((bytesLoaded / bytesTotal) * 100) + "%");
} }
//上传成功 //上传成功
function uploadSuccess(file, serverData, res) function uploadSuccess(file, serverData, res) {
{ var id = "handle_button_" + file.id;
var id = "handle_button_"+file.id; $("#" + id).replaceWith("<dd>" + jsonLang.t10 + "</dd>")
$("#"+id).replaceWith("<dd>"+jsonLang.t10+"</dd>")
} }
//取消上传 //取消上传
function userCancelUpload(file_id, type) function userCancelUpload(file_id, type) {
{
if(type==0){ if (type == 0) {
SWFFuns.cancelUpload(file_id); SWFFuns.cancelUpload(file_id);
}else{ } else {
HTML5Funs.cancelUpload(file_id); HTML5Funs.cancelUpload(file_id);
} }
$("#handle_button_"+file_id).html(jsonLang.t14).removeClass("orange").addClass("gray"); $("#handle_button_" + file_id).html(jsonLang.t14).removeClass("orange").addClass("gray");
//如果已经上传一部分了 //如果已经上传一部分了
if($("#progress_bar_p_"+file_id).hasClass("orange")){ if ($("#progress_bar_p_" + file_id).hasClass("orange")) {
$("#progress_bar_p_"+file_id).removeClass("orange"); $("#progress_bar_p_" + file_id).removeClass("orange");
$("#progress_bar_p_"+file_id).addClass("gray"); $("#progress_bar_p_" + file_id).addClass("gray");
} }
} }
@ -193,10 +185,10 @@ function userCancelUpload(file_id, type)
* 通过文件名称 从全局的文件列表中获取文件对象 * 通过文件名称 从全局的文件列表中获取文件对象
* *
*/ */
function getFileFomeFilesUpload(filename){ function getFileFomeFilesUpload(filename) {
var len = filesUpload.length; var len = filesUpload.length;
for(var i=0; i < len; i++){ for (var i = 0; i < len; i++) {
if(filesUpload[i].name == filename){ if (filesUpload[i].name == filename) {
return filesUpload[i]; return filesUpload[i];
} }
} }
@ -208,12 +200,12 @@ function getFileFomeFilesUpload(filename){
/** /**
* 往全局的 上传列表添加一个数据 * 往全局的 上传列表添加一个数据
*/ */
function addFileToFilesUpload(file){ function addFileToFilesUpload(file) {
if(typeof file == "string"){ if (typeof file == "string") {
filesUpload.push({"name":file}) filesUpload.push({ "name": file })
return true; return true;
}else if(typeof file == "object"){ } else if (typeof file == "object") {
filesUpload.push(file); filesUpload.push(file);
return true; return true;
} }
@ -224,11 +216,11 @@ function addFileToFilesUpload(file){
/** /**
* 往全局的 上传列表添加一个数据 * 往全局的 上传列表添加一个数据
*/ */
function updateFileToFilesUpload(file){ function updateFileToFilesUpload(file) {
var len = filesUpload.length; var len = filesUpload.length;
for(var i=0; i < len; i++){ for (var i = 0; i < len; i++) {
if(filesUpload[i].name == file.name){ if (filesUpload[i].name == file.name) {
filesUpload[i] = file; filesUpload[i] = file;
return true; return true;
} }
@ -240,10 +232,10 @@ function updateFileToFilesUpload(file){
/** /**
* 查找在数组中的位置 * 查找在数组中的位置
*/ */
function findObjectKey (object, fid){ function findObjectKey(object, fid) {
var len = object.length; var len = object.length;
for(var i=0; i<len; i++){ for (var i = 0; i < len; i++) {
if(object[i].id == fid){ if (object[i].id == fid) {
return i; return i;
} }
} }
@ -256,13 +248,13 @@ function findObjectKey (object, fid){
* @param int fid 要删除的文件id * @param int fid 要删除的文件id
* @return 删除后的数组 其实数组是引用类型可以不返回 * @return 删除后的数组 其实数组是引用类型可以不返回
*/ */
function removeFileFromFilesUpload(files, fid){ function removeFileFromFilesUpload(files, fid) {
var filesUploadKey = -1; var filesUploadKey = -1;
filesUploadKey = findObjectKey(files, fid); filesUploadKey = findObjectKey(files, fid);
//从全局文件中移除 //从全局文件中移除
if(filesUploadKey > -1) if (filesUploadKey > -1)
files.splice(filesUploadKey, 1); files.splice(filesUploadKey, 1);
return files; return files;

@ -1,28 +1,28 @@
/** /**
* 处理拖拽上传 * 处理拖拽上传
*/ */
var isDragOver = false;//拖拽触发点 var isDragOver = false;//拖拽触发点
var fileNumber = -1; //上传文件编号 var fileNumber = -1; //上传文件编号
var fileNumberPex = "zyFileUpload_"; //编号前缀 var fileNumberPex = "zyFileUpload_"; //编号前缀
var currUploadfile = {}; //当前上传的文件对象 var currUploadfile = {}; //当前上传的文件对象
var uploadQueue = [];//上传队列集合 var uploadQueue = [];//上传队列集合
var isUploading = false;//是否正在上传 var isUploading = false;//是否正在上传
var XHR var XHR
try{ try {
XHR = new XMLHttpRequest(); XHR = new XMLHttpRequest();
}catch(e){} } catch (e) { }
(function(isSupportFileUpload){ (function (isSupportFileUpload) {
//不支持拖拽上传,或者 不支持FormData ,显示WiFi表示 //不支持拖拽上传,或者 不支持FormData ,显示WiFi表示
if(!isSupportFileUpload){ if (!isSupportFileUpload) {
$("#drag_area").addClass("wf_wifi"); $("#drag_area").addClass("wf_wifi");
$("#drag_area h3").html(""); $("#drag_area h3").html("");
return; return;
//更换样式 //更换样式
}else{ } else {
$("#drag_area").addClass("wf_normal"); $("#drag_area").addClass("wf_normal");
} }
@ -32,7 +32,7 @@
/** /**
* 添加事件 * 添加事件
*/ */
function addEvent(){ function addEvent() {
var dropArea = $('#drag_area h3')[0]; var dropArea = $('#drag_area h3')[0];
dropArea.addEventListener('dragover', handleDragOver, false); dropArea.addEventListener('dragover', handleDragOver, false);
dropArea.addEventListener('dragleave', handleDragLeave, false); dropArea.addEventListener('dragleave', handleDragLeave, false);
@ -42,7 +42,7 @@
/** /**
* 松开拖拽文件的处理进行上传 * 松开拖拽文件的处理进行上传
*/ */
function handleDrop(evt){ function handleDrop(evt) {
evt.stopPropagation(); evt.stopPropagation();
evt.preventDefault(); evt.preventDefault();
@ -51,50 +51,50 @@
console.log("Drop"); console.log("Drop");
isDragOver = false; isDragOver = false;
var file={}; var file = {};
var errorMsgs = []; var errorMsgs = [];
var len = evt.dataTransfer.files.length; var len = evt.dataTransfer.files.length;
for(var i=0; i < len; i++){ for (var i = 0; i < len; i++) {
fileNumber ++ ; fileNumber++;
file = evt.dataTransfer.files[i]; file = evt.dataTransfer.files[i];
file.id = fileNumberPex+fileNumber; file.id = fileNumberPex + fileNumber;
//检测文件 //检测文件
msg = checkFile(file) msg = checkFile(file)
//文件可以通过 //文件可以通过
if(!msg){ if (!msg) {
//添加全局 //添加全局
filesUpload.push(file); filesUpload.push(file);
//添加上传队列 //添加上传队列
uploadQueue.push(file); uploadQueue.push(file);
//在页面进行展示 //在页面进行展示
fileQueued(file, 1); fileQueued(file, 1);
}else{ } else {
errorMsgs.push(msg) errorMsgs.push(msg)
} }
} }
if(errorMsgs.length>0){ if (errorMsgs.length > 0) {
//只选择做一个进行上传 //只选择做一个进行上传
if(len==1){ if (len == 1) {
alert(errorMsgs[0]); alert(errorMsgs[0]);
}else{ } else {
a1=len; a1 = len;
a2=len - errorMsgs.length; a2 = len - errorMsgs.length;
var replaceArr = new Array(a1,a2); var replaceArr = new Array(a1, a2);
alert(stringReplace(jsonLang.t7,replaceArr)); alert(stringReplace(jsonLang.t7, replaceArr));
} }
} }
//拿出第一个,进行上传 //拿出第一个,进行上传
if(!isUploading && uploadQueue.length>0) uploadFiles(uploadQueue.shift()); if (!isUploading && uploadQueue.length > 0) uploadFiles(uploadQueue.shift());
} }
function handleDragOver(evt){ function handleDragOver(evt) {
evt.stopPropagation(); evt.stopPropagation();
evt.preventDefault(); evt.preventDefault();
@ -108,7 +108,7 @@
} }
function handleDragLeave(evt){ function handleDragLeave(evt) {
console.log("DragLeave"); console.log("DragLeave");
evt.stopPropagation(); evt.stopPropagation();
@ -119,7 +119,7 @@
function uploadFiles(file){ function uploadFiles(file) {
//正在上传 //正在上传
isUploading = true; isUploading = true;
//设置上传的数据 //设置上传的数据
@ -129,7 +129,7 @@
fd.append("Upload", "Submit Query"); fd.append("Upload", "Submit Query");
//设置当前的上传对象 //设置当前的上传对象
currUploadfile = file; currUploadfile = file;
if(XHR.readyState>0){ if (XHR.readyState > 0) {
XHR = new XMLHttpRequest(); XHR = new XMLHttpRequest();
} }
@ -140,17 +140,17 @@
XHR.upload.addEventListener("loadend", loadend, false); XHR.upload.addEventListener("loadend", loadend, false);
XHR.upload.addEventListener("loadstart", loadstart, false); XHR.upload.addEventListener("loadstart", loadstart, false);
XHR.open("POST", config.url); XHR.open("POST", config.url);
XHR.setRequestHeader("Content-Type","application/octet-stream"); XHR.setRequestHeader("Content-Type", "multipart/mixed stream");
XHR.send(fd); XHR.send(fd);
XHR.onreadystatechange = function() { XHR.onreadystatechange = function () {
//只要上传完成不管成功失败 //只要上传完成不管成功失败
if (XHR.readyState == 4 ){ if (XHR.readyState == 4) {
console.log("onreadystatechange " , XHR.status, +new Date()); console.log("onreadystatechange ", XHR.status, +new Date());
if(XHR.status == 200){ if (XHR.status == 200) {
uploadSuccess(currUploadfile, {}, XHR.status) uploadSuccess(currUploadfile, {}, XHR.status)
}else{ } else {
uploadError() uploadError()
} }
@ -162,26 +162,26 @@
} }
//请求完成,无论失败或成功 //请求完成,无论失败或成功
function loadend(evt){ function loadend(evt) {
console.log("loadend",+new Date(),evt); console.log("loadend", +new Date(), evt);
} }
//请求开始 //请求开始
function loadstart(evt){ function loadstart(evt) {
console.log("loadstart",evt); console.log("loadstart", evt);
} }
//在请求发送或接收数据期间,在服务器指定的时间间隔触发。 //在请求发送或接收数据期间,在服务器指定的时间间隔触发。
function progress(evt){ function progress(evt) {
uploadProgress(currUploadfile, evt.loaded || evt.position , evt.total) uploadProgress(currUploadfile, evt.loaded || evt.position, evt.total)
} }
//在请求被取消时触发,例如,在调用 abort() 方法时。 //在请求被取消时触发,例如,在调用 abort() 方法时。
function abort(evt){ function abort(evt) {
console.log("abort",evt); console.log("abort", evt);
} }
//在请求失败时触发。 //在请求失败时触发。
function error(evt){ function error(evt) {
//终止ajax请求 //终止ajax请求
XHR.abort(); XHR.abort();
uploadError() uploadError()
@ -189,27 +189,27 @@
} }
//在请求成功完成时触发。 //在请求成功完成时触发。
function requestLoad(evt){ function requestLoad(evt) {
console.log("requestLoad", +new Date(),evt); console.log("requestLoad", +new Date(), evt);
} }
//进行下一个上传 //进行下一个上传
function nextUpload(){ function nextUpload() {
isUploading = false; isUploading = false;
if(uploadQueue.length>0){ if (uploadQueue.length > 0) {
uploadFiles(uploadQueue.shift()); uploadFiles(uploadQueue.shift());
}else{ } else {
//米有正在上传的了 //米有正在上传的了
currUploadfile = {} currUploadfile = {}
} }
} }
//上传出错误了,比如断网, //上传出错误了,比如断网,
function uploadError(){ function uploadError() {
//移除全局变量中的,上传出错的 //移除全局变量中的,上传出错的
removeFileFromFilesUpload(filesUpload, currUploadfile.id) removeFileFromFilesUpload(filesUpload, currUploadfile.id)
var file = currUploadfile; var file = currUploadfile;
$("#handle_button_"+file.id).replaceWith("<dd>"+jsonLang.t8+"</dd>") $("#handle_button_" + file.id).replaceWith("<dd>" + jsonLang.t8 + "</dd>")
} }
@ -219,7 +219,7 @@
* 取消上传 * 取消上传
* @param string fid 文件的Id * @param string fid 文件的Id
*/ */
cancelUpload : function(fid){ cancelUpload: function (fid) {
var filesUploadKey = -1; var filesUploadKey = -1;
var uploadQueueKey = -1; var uploadQueueKey = -1;
@ -229,9 +229,9 @@
removeFileFromFilesUpload(filesUpload, fid) removeFileFromFilesUpload(filesUpload, fid)
//如果是正在上传的,AJAX取消 //如果是正在上传的,AJAX取消
if(currUploadfile.id == fid){ if (currUploadfile.id == fid) {
XHR.abort(); XHR.abort();
}else{ } else {
//从上传队列中移除 //从上传队列中移除
removeFileFromFilesUpload(uploadQueue, fid) removeFileFromFilesUpload(uploadQueue, fid)
} }

@ -3,39 +3,41 @@
* 切换语言环境 addby zhongweikang@zhangyue.com 2015/09/23 * 切换语言环境 addby zhongweikang@zhangyue.com 2015/09/23
*/ */
var language;//当前语言 var language;//当前语言
var jsonEn;//英文 var jsonEn;//英文
var jsonZh;//中文 var jsonZh;//中文
/** /**
* 语言包 * 语言包
*/ */
jsonEn = { t0:"WiFi Upload",t1:"Documents",t2:"Name",t3:"Size",t4:"Operation", jsonEn = {
t5:"Supported Format:TXT、EPUB、UMD",t6:"Drag here and Drop to upload", t0: "WiFi Upload", t1: "Documents", t2: "Name", t3: "Size", t4: "Operation",
t7:"You choosed [txt] files ,we only can upload [txt] of them。\nPlease choose TXT、EPUB、UMD files, file name cannot be repeated.", t5: "Supported Format:TXT、EPUB、UMD", t6: "Drag here and Drop to upload",
t8:"Failed",t9:"Cancel",t10:"Done",t11:"One of books is over 500MB",t12:"Bad file mode", t7: "You choosed [txt] files ,we only can upload [txt] of them。\nPlease choose TXT、EPUB、UMD files, file name cannot be repeated.",
t13:"File already exists",t14:"Canceled" t8: "Failed", t9: "Cancel", t10: "Done", t11: "One of books is over 500MB", t12: "Bad file mode",
}; t13: "File already exists", t14: "Canceled"
jsonZh = { t0:"WiFi 下载",t1:"文档",t2:"名字",t3:"大小",t4:"操作", };
t5:"支持类型:TXT、EPUB、UMD",t6:"拖至此处上传", jsonZh = {
t7:"你选择了[txt]个文件,我们只能上传其中的[txt]。\n请选择 TXT、EPUB、UMD 类型的文件,文件的名字不能重复。", t0: "传书", t1: "文档", t2: "名字", t3: "大小", t4: "操作",
t8:"失败",t9:"取消",t10:"完成",t11:"上传文件不能大于500MB",t12:"无效的文件格式", t5: "支持类型:TXT、EPUB、UMD", t6: "拖至此处上传",
t13:"文件已存在",t14:"已取消" t7: "你选择了[txt]个文件,我们只能上传其中的[txt]。\n请选择 TXT、EPUB、UMD 类型的文件,文件的名字不能重复。",
}; t8: "失败", t9: "取消", t10: "完成", t11: "上传文件不能大于500MB", t12: "无效的文件格式",
t13: "文件已存在", t14: "已取消"
};
if (navigator.language) { if (navigator.language) {
language = navigator.language; language = navigator.language;
} }
else { else {
language = navigator.browserLanguage; language = navigator.browserLanguage;
} }
language = language.toLowerCase(language); language = language.toLowerCase(language);
/** /**
* 切换语言 * 切换语言
*/ */
function langSwich(s){ function langSwich(s) {
switch(s){ switch (s) {
case 'en-us': case 'en-us':
_strReplace(jsonEn); _strReplace(jsonEn);
break; break;
@ -46,43 +48,42 @@
_strReplace(jsonEn); _strReplace(jsonEn);
break; break;
} }
} }
function _strReplace(d){ function _strReplace(d) {
window.jsonLang=d;//全局变量在其他js文件中会遇到,勿删。 window.jsonLang = d;//全局变量在其他js文件中会遇到,勿删。
for(var i in jsonLang){ for (var i in jsonLang) {
$('[data-js=' + i + ']').html(d[i]) $('[data-js=' + i + ']').html(d[i])
} }
} }
/** /**
* 特殊字符串替换语言包中的 t7 * 特殊字符串替换语言包中的 t7
* content 替换前的文本 * content 替换前的文本
* replace 待插入的文本 支持变量或数组 * replace 待插入的文本 支持变量或数组
*/ */
var isArray = function(obj) { var isArray = function (obj) {
return Object.prototype.toString.call(obj) === '[object Array]'; return Object.prototype.toString.call(obj) === '[object Array]';
} }
function stringReplace(content,replace){ function stringReplace(content, replace) {
var str = content; var str = content;
if(!str){return null;} if (!str) { return null; }
if(isArray(replace)){ if (isArray(replace)) {
strs=str.split("[txt]"); strs = str.split("[txt]");
count = strs.length-1; count = strs.length - 1;
var string = ''; var string = '';
for(var i=0;i<count;i++){ for (var i = 0; i < count; i++) {
string = string+strs[i]+replace[i]; string = string + strs[i] + replace[i];
} }
string = string+strs[count]; string = string + strs[count];
}else{ } else {
string=str.replace(replace,"[txt]"); string = str.replace(replace, "[txt]");
} }
return string; return string;
} }
//执行
langSwich(language);
//执行
langSwich(language);

@ -4,24 +4,23 @@
var swfu;//swfupload 对象 var swfu;//swfupload 对象
var swfSelectCount = 0;// 当前选中的文件数量 var swfSelectCount = 0;// 当前选中的文件数量
window.onload = function() { window.onload = function () {
var settings = { var settings = {
flash_url : "js/swfupload.swf",
upload_url: config.url, upload_url: config.url,
/*post_params: {"PHPSESSID" : "<?php echo session_id(); ?>"},*/ /*post_params: {"PHPSESSID" : "<?php echo session_id(); ?>"},*/
file_size_limit : config.fileLimitSize+" B", file_size_limit: config.fileLimitSize + " B",
file_types : "*."+config.fileTypes.split("|").join(";*."), file_types: "*." + config.fileTypes.split("|").join(";*."),
file_types_description : "All Files", file_types_description: "All Files",
file_upload_limit : 1000, //配置上传个数 file_upload_limit: 1000, //配置上传个数
file_queue_limit : 0, file_queue_limit: 0,
custom_settings : { custom_settings: {
progressTarget : "fsUploadProgress", progressTarget: "fsUploadProgress",
cancelButtonId : "btnCancel" cancelButtonId: "btnCancel"
}, },
debug: 0, debug: 0,
button_cursor:SWFUpload.CURSOR.HAND, button_cursor: SWFUpload.CURSOR.HAND,
button_image_url: "i/wifi_btn_b.png", button_image_url: "i/wifi_btn_b.png",
button_width: "240", button_width: "240",
button_height: "100", button_height: "100",
@ -29,37 +28,34 @@ window.onload = function() {
button_placeholder_id: "spanButtonPlaceHolder", button_placeholder_id: "spanButtonPlaceHolder",
button_text: '<span class="theFont"></span>', button_text: '<span class="theFont"></span>',
assume_success_timeout:30, assume_success_timeout: 30,
file_queued_handler : swfFileQueued, file_queued_handler: swfFileQueued,
file_queue_error_handler : fileQueueError, file_queue_error_handler: fileQueueError,
file_dialog_complete_handler : fileDialogComplete, file_dialog_complete_handler: fileDialogComplete,
upload_start_handler : uploadStart, upload_start_handler: uploadStart,
upload_progress_handler : uploadProgress, upload_progress_handler: uploadProgress,
upload_error_handler : uploadError, upload_error_handler: uploadError,
upload_success_handler : uploadSuccess, upload_success_handler: uploadSuccess,
upload_complete_handler : uploadComplete, upload_complete_handler: uploadComplete,
queue_complete_handler : queueComplete queue_complete_handler: queueComplete
}; };
swfu = new SWFUpload(settings); swfu = new SWFUpload(settings);
}; };
//上传完成 //上传完成
function uploadComplete(file,server,response) function uploadComplete(file, server, response) {
{
//继续下一个文件的上传 //继续下一个文件的上传
this.startUpload(); this.startUpload();
} }
//完成队列里的上传 //完成队列里的上传
function queueComplete(numFilesUploaded) function queueComplete(numFilesUploaded) {
{
} }
function userStartUpload(file_id) function userStartUpload(file_id) {
{
swfu.startUpload(file_id); swfu.startUpload(file_id);
} }
@ -67,9 +63,8 @@ function userStartUpload(file_id)
function fileQueueError(file, errorCode, message) function fileQueueError(file, errorCode, message) {
{ switch (errorCode) {
switch(errorCode){
case -100: case -100:
//alert("Over 100 books"); //alert("Over 100 books");
case -110: case -110:
@ -81,22 +76,18 @@ function fileQueueError(file, errorCode, message)
} }
} }
//入列完毕 //入列完毕
function fileDialogComplete(numFilesSelected, numFilesQueued) function fileDialogComplete(numFilesSelected, numFilesQueued) {
{ if (numFilesSelected > 0) {
if (numFilesSelected > 0)
{
this.startUpload() this.startUpload()
} }
} }
//开始上传 //开始上传
function uploadStart(file) function uploadStart(file) {
{
return true; return true;
} }
//上传出错 //上传出错
function uploadError(file, errorCode, message) function uploadError(file, errorCode, message) {
{
switch (errorCode) { switch (errorCode) {
case SWFUpload.UPLOAD_ERROR.HTTP_ERROR: case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
errorMessage = "Error"; errorMessage = "Error";
@ -126,7 +117,7 @@ function uploadError(file, errorCode, message)
errorMessage = jsonLang.t8; errorMessage = jsonLang.t8;
$("#handle_button_"+file.id).replaceWith("<dd>"+errorMessage+"</dd>") $("#handle_button_" + file.id).replaceWith("<dd>" + errorMessage + "</dd>")
} }
@ -134,22 +125,22 @@ var tmp = 0;
var errorFile = 0; var errorFile = 0;
var errorMsgs = []; var errorMsgs = [];
function swfFileQueued(file){ function swfFileQueued(file) {
//本次上传选中的文件个数 //本次上传选中的文件个数
if(swfSelectCount==0) swfSelectCount = this.getStats().files_queued if (swfSelectCount == 0) swfSelectCount = this.getStats().files_queued
//检测文件 //检测文件
msg = checkFile(file) msg = checkFile(file)
//文件可以通过 //文件可以通过
if(!msg){ if (!msg) {
//添加全局的队列 //添加全局的队列
filesUpload.push(file); filesUpload.push(file);
//在页面进行展示 //在页面进行展示
fileQueued(file, 0) fileQueued(file, 0)
}else{ } else {
//从上传队列移除,验证失败的文件 //从上传队列移除,验证失败的文件
this.cancelUpload(file.id, false) this.cancelUpload(file.id, false)
errorMsgs.push(msg) errorMsgs.push(msg)
@ -158,18 +149,18 @@ function swfFileQueued(file){
//队列选择完毕,初始化所有的数据 //队列选择完毕,初始化所有的数据
if(++tmp == swfSelectCount){ if (++tmp == swfSelectCount) {
if(errorMsgs.length>0){ if (errorMsgs.length > 0) {
//只选择做一个进行上传 //只选择做一个进行上传
if(swfSelectCount==1){ if (swfSelectCount == 1) {
alert(errorMsgs[0]); alert(errorMsgs[0]);
}else{ } else {
a1=swfSelectCount; a1 = swfSelectCount;
a2=swfSelectCount - errorMsgs.length; a2 = swfSelectCount - errorMsgs.length;
var replaceArr = new Array(a1,a2); var replaceArr = new Array(a1, a2);
alert(stringReplace(jsonLang.t7,replaceArr)); alert(stringReplace(jsonLang.t7, replaceArr));
} }
} }
@ -185,7 +176,7 @@ function swfFileQueued(file){
var SWFFuns = { var SWFFuns = {
cancelUpload : function(fid){ cancelUpload: function (fid) {
swfu.cancelUpload(fid, false); swfu.cancelUpload(fid, false);
} }

@ -197,8 +197,9 @@ object BookController {
DiskFileItemFactory(0, LocalBook.cacheFolder) DiskFileItemFactory(0, LocalBook.cacheFolder)
} }
fun addLocalBook(session: NanoHTTPD.IHTTPSession): ReturnData { fun addLocalBook(session: NanoHTTPD.IHTTPSession, postData: String?): ReturnData {
val returnData = ReturnData() val returnData = ReturnData()
try {
NanoFileUpload(bookFileFactory).parseRequest(session).forEach { NanoFileUpload(bookFileFactory).parseRequest(session).forEach {
val path = FileUtils.getPath(LocalBook.cacheFolder, it.name) val path = FileUtils.getPath(LocalBook.cacheFolder, it.name)
val nameAuthor = LocalBook.analyzeNameAuthor(it.name) val nameAuthor = LocalBook.analyzeNameAuthor(it.name)
@ -217,6 +218,12 @@ object BookController {
if (book.isUmd()) UmdFile.upBookInfo(book) if (book.isUmd()) UmdFile.upBookInfo(book)
appDb.bookDao.insert(book) appDb.bookDao.insert(book)
} }
} catch (e: Exception) {
e.printStackTrace()
return returnData.setErrorMsg(
e.localizedMessage ?: appCtx.getString(R.string.unknown_error)
)
}
return returnData.setData(true) return returnData.setData(true)
} }

@ -21,8 +21,8 @@ class HttpServer(port: Int) : NanoHTTPD(port) {
var uri = session.uri var uri = session.uri
try { try {
when (session.method.name) { when (session.method) {
"OPTIONS" -> { Method.OPTIONS -> {
val response = newFixedLengthResponse("") val response = newFixedLengthResponse("")
response.addHeader("Access-Control-Allow-Methods", "POST") response.addHeader("Access-Control-Allow-Methods", "POST")
response.addHeader("Access-Control-Allow-Headers", "content-type") response.addHeader("Access-Control-Allow-Headers", "content-type")
@ -30,7 +30,7 @@ class HttpServer(port: Int) : NanoHTTPD(port) {
//response.addHeader("Access-Control-Max-Age", "3600"); //response.addHeader("Access-Control-Max-Age", "3600");
return response return response
} }
"POST" -> { Method.POST -> {
val files = HashMap<String, String>() val files = HashMap<String, String>()
session.parseBody(files) session.parseBody(files)
val postData = files["postData"] val postData = files["postData"]
@ -40,11 +40,11 @@ class HttpServer(port: Int) : NanoHTTPD(port) {
"/saveSources" -> SourceController.saveSources(postData) "/saveSources" -> SourceController.saveSources(postData)
"/saveBook" -> BookController.saveBook(postData) "/saveBook" -> BookController.saveBook(postData)
"/deleteSources" -> SourceController.deleteSources(postData) "/deleteSources" -> SourceController.deleteSources(postData)
"/addLocalBook" -> BookController.addLocalBook(session) "/addLocalBook" -> BookController.addLocalBook(session, postData)
else -> null else -> null
} }
} }
"GET" -> { Method.GET -> {
val parameters = session.parameters val parameters = session.parameters
returnData = when (uri) { returnData = when (uri) {
@ -58,6 +58,7 @@ class HttpServer(port: Int) : NanoHTTPD(port) {
else -> null else -> null
} }
} }
else -> Unit
} }
if (returnData == null) { if (returnData == null) {

Loading…
Cancel
Save