var lock_uploadenable = false; var upload_queue = []; var filenow_xhr_slot = []; var filenow_filecnt = 0; var filenow_filesize = 0; var timer_checkQueue = false; var upload_cancel = false; function uploadFile(_filedata, _callback) { if (!lock_uploadenable) return; if (!checkUploadFinished()) { viewUploadError(false, "別のアップロードが進行中です。"); return; } if (_filedata.length <= 0) { return; } $('.area_fileupload').css("display", "none"); $('.area_waitupload').css("display", "block"); //進行中に追加 var append = false; if (upload_queue.length > 0) { append = true; } if (!append) { updateUploadStatus(0, "しばらくおまちください..."); } var now_filecnt = 0; var now_filesize = 0; for (var i=0; i<_filedata.length; i++) { if (!_filedata[i].name || _filedata[i].size <= 0) continue; now_filecnt ++; now_filesize += _filedata[i].size; upload_queue[upload_queue.length] = { id: upload_queue.length, filedata: _filedata[i], status: "wait", loaded: 0, server: false, url: "", hash: "", callback: _callback }; } console.log("upload_queue: ", upload_queue); if (now_filecnt <= 0) { uploadClean(true); return; } if (filenow_filecnt+now_filecnt > 300) { //ファイル数制限を超えている viewUploadError(false, "ファイル個数制限を超えています。同時に300個までのファイルを送信できます。"); uploadClean(true); return; } if (filenow_filesize+now_filesize >= 1024*1024*102400) { //ファイル制限超えてる viewUploadError(false, "サイズ制限を超えています。合計100GB (100,000MB)までのファイルを送信できます。"); uploadClean(true); return; } filenow_filecnt = now_filecnt; filenow_filesize = now_filesize; console.log("total filecnt="+filenow_filecnt+", filesize="+Math.round(filenow_filesize/(1024*1024))+"MB"); console.log("upload_queue: ", upload_queue); var postData = {}; postData.action = "getUploadURL"; var upload_files = {}; for (var i in upload_queue) { upload_files[upload_queue[i].id] = { "filename": upload_queue[i].filedata.name, "size": upload_queue[i].filedata.size }; } if (typeof uploadFileLists == 'function') { uploadFileLists(upload_files); } postData.upload_files = JSON.stringify(upload_files); $.ajax({ url: "https://d.kuku.lu/_server.php", type: 'POST', cache: false, data: postData, dataType: "json" }).done(function(data){ if (data.result == "OK" && data.servers) { for (var i in data.servers) { upload_queue[i]["server"] = data.servers[i]; } console.log("upload_queue: ", upload_queue); if (!append) upload_start_time = (new Date().getTime()); if (timer_checkQueue) { clearInterval(timer_checkQueue); } timer_checkQueue = setInterval(checkQueue, 200); } else { viewUploadError(false, "現在サービスの問題のため一時的にアップロードができません。しばらく待ってから再度お試しください。"); uploadClean(true); } }).fail(function(){ viewUploadError("getServerFailed"); uploadClean(true); }); } function checkQueue() { uploadProgress(); //現在のパラレル数、完了数を取得 var _now_upload_cnt = 0; var _now_complete_cnt = 0; for (var i=0; i= upload_queue.length) { //checkQueueを止める if (timer_checkQueue) { clearInterval(timer_checkQueue); timer_checkQueue = false; } finishUploadQueue(); return; } //パラレル数が4未満なら新規アップロード開始 if (_now_upload_cnt < 4) { for (var n=0; n<(4-_now_upload_cnt); n++) { for (var i=0; i= 100) { updateUploadStatus(false, '登録処理中です。ファイル数や容量によっては時間がかかります...'); } else { var _speed_bps = 0; var _lefttime = ""; try { if (upload_start_time && filenow_filesize && _totalloaded) { _speed_bps = (_totalloaded/(((new Date().getTime()) - upload_start_time)/1024)); var _lefttime_sec = Math.ceil((filenow_filesize-_totalloaded) / _speed_bps); var _lefttime_min = Math.floor(_lefttime_sec / 60); _lefttime_sec -= _lefttime_min * 60; _lefttime = "(残り "; if (_lefttime_min) { _lefttime += ""+Math.ceil(_lefttime_min)+"分"; } _lefttime += ""+Math.ceil(_lefttime_sec)+"秒"; _lefttime += ")"; } } catch(e) { console.error(e); } updateUploadStatus(false, ""+viewBytes(_totalloaded)+" / "+viewBytes(filenow_filesize)+" - "+viewBytes(_speed_bps, "KB")+"/s - "+ percentComplete.toString() + "% 完了
"+_lefttime); } } function startUpload(_queue_pos) { var _id = upload_queue[_queue_pos].id; console.log("startUpload", _id, upload_queue[_id]); var _method = upload_queue[_id]["server"]["method"]; var _file_key = upload_queue[_id]["server"]["file_key"]; filenow_xhr_slot[_id] = new XMLHttpRequest(); var xhr = filenow_xhr_slot[_id]; if (_method == "post") { var fd = new FormData(); fd.append("ajax", "1"); fd.append("uuid", "ed06555336ddd95303b596593174a3eb"); fd.append("country", "US"); fd.append("file_1", upload_queue[_id]["filedata"]); fd.append("file_1_name", upload_queue[_id]["filedata"].name); fd.append("file_1_type", upload_queue[_id]["filedata"].type); fd.append("filecnt", 1); } xhr.upload.addEventListener("progress", function(e) { upload_queue[_id].loaded = e.loaded; }, false); xhr.addEventListener("load", function(e) { console.log("upload complete: ", _id, e); if (_method == "put") { var promise_genthum; //ローカルサムネ作成 genThumb( { "file": upload_queue[_id]["filedata"], "size_min": 2*1024*1024, "size_max": 25*1024*1024, "width": 800, "height": 600 }, function(_thumimg){ if (!_thumimg) _thumimg = ""; $.ajax({ url: "https://d.kuku.lu/_server.php", type: 'POST', cache: false, dataType: "json", data:"&action=registerFileByUser&uuid=ed06555336ddd95303b596593174a3eb&file_key="+encodeURIComponent(_file_key)+"&thumimg="+encodeURIComponent(_thumimg), }).done(function(data){ if (data["result"] == "OK") { upload_queue[_id].status = "complete"; upload_queue[_id].url = data["url"]; upload_queue[_id].hash = data["hash"]; if (upload_queue[_id].callback) { upload_queue[_id].callback(false, {"url": upload_queue[_id].url, "hash": upload_queue[_id].hash}); } } else if (data["msg"]) { viewUploadError(false, data["msg"]); upload_queue[_id].status = "error"; } else { viewUploadError("responseFailed"); upload_queue[_id].status = "error"; } }).fail(function(){ viewUploadError("registerFailed"); upload_queue[_id].status = "error"; }); } ); } else { var _res = e.target.responseText; if (_res.indexOf("OK:") == 0) { upload_queue[_id].status = "complete"; upload_queue[_id].url = _res.replace("OK:", ""); upload_queue[_id].hash = _res.replace("OK:https://d.kuku.lu/", ""); if (upload_queue[_id].callback) { upload_queue[_id].callback(false, {"url": upload_queue[_id].url, "hash": upload_queue[_id].hash}); } } else if (_res.indexOf("NG:") == 0) { var _tmp = _res.replace("NG:", ""); viewUploadError(false, ""+_tmp); upload_queue[_id].status = "error"; } else { viewUploadError("responseFailed"); upload_queue[_id].status = "error"; } } }, false); xhr.addEventListener("error", function(e) { if (!upload_cancel) { viewUploadError("uploadFailed"); upload_queue[_id].status = "error"; } try { filenow_xhr_slot[_id].abort(); filenow_xhr_slot[_id] = null; } catch(e) { console.log(e); } }, false); xhr.addEventListener("abort", function(e) { if (!upload_cancel) { upload_queue[_id].status = "error"; } try { filenow_xhr_slot[_id].abort(); filenow_xhr_slot[_id] = null; } catch(e) { console.log(e); } }, false); if (_method == "put") { xhr.open("PUT", upload_queue[_id]["server"]["url"]); xhr.send(upload_queue[_id]["filedata"]); } else { xhr.open("POST", upload_queue[_id]["server"]["url"]); xhr.send(fd); } } function uploadCancel() { upload_cancel = true; if (timer_checkQueue) { clearInterval(timer_checkQueue); timer_checkQueue = false; } $('.area_fileupload').css("display", "block"); $('.area_waitupload').css("display", "none"); console.log("filenow_xhr_slot: ", filenow_xhr_slot); for (var i=0; i= 100) _percent = 100; $('.area_uploadprogress').css("width", ""+_percent+"%"); } if (typeof updateUploadStatusAlt == 'function') { updateUploadStatusAlt(_percent, _message); } } function viewUploadError(_code, _message) { if (upload_cancel) return; if (typeof viewUploadErrorAlt == 'function') { viewUploadErrorAlt(_code, _message); } else { if (_message) { alert(_message); } else { alert("ファイルの送信中にエラーが発生しました。もう一度お試しください。 ("+_code+")"); } } } function viewBytes(num, _format){ var _suff = "KB"; if (num >= 1024*1024 && (!_format || _format == "MB")) { //MB num = Math.round((num) / (1024*1024)); _suff = "MB"; } else { //KB num = Math.round((num) / 1024); _suff = "KB"; } return ""+(String(num).replace( /(\d)(?=(\d\d\d)+(?!\d))/g, '$1,'))+" "+_suff; } $(function(){ $("#file_upload").change(function(){ uploadFile(document.getElementById('file_upload').files); }); $(".button_upload").click(function(){ var $elm = $('#file_upload'); if (document.createEvent) { $elm.show(); var e = document.createEvent('MouseEvents'); e.initEvent('click', true, true ); $elm.get(0).dispatchEvent(e); $elm.hide(); } else { $elm.show(); $elm.trigger("click"); $elm.hide(); } return false; }); $(".area_fileupload_drop").bind("dragover", function(e){ e.originalEvent.preventDefault(); return false; }); $(".area_fileupload_drop").bind("dropstart", function(e){ e.originalEvent.preventDefault(); e.originalEvent.stopPropagation(); return false; }); $(".area_fileupload_drop").bind("drop", function(e){ e.originalEvent.preventDefault(); e.originalEvent.stopPropagation(); console.log(e.type, e.target.id); console.log(e.originalEvent.dataTransfer.files); $(".area_fileupload_drop").css("display", "none"); $(".area_fileupload").css("display", "block"); uploadFile(e.originalEvent.dataTransfer.files); return false; }); var next_dragleave_cancel = false; $("body").bind("dragenter", function(e){ e.originalEvent.preventDefault(); console.log(e.type, e.target.id, e.originalEvent); if ($(e.target).closest(".area_fileupload").length > 0) { $(".area_fileupload_drop_here").css("height", $(".area_fileupload").height()); $(".area_fileupload").css("display", "none"); $(".area_fileupload_drop").css("display", "block"); } if ($(e.target).closest(".area_fileupload_fixed").length > 0) { $(".area_fileupload_drop").css("display", "block"); } if (!$(e.target).hasClass('area_fileupload_drop_here') && $(e.target).closest(".area_fileupload_drop_here").length > 0) { next_dragleave_cancel = true; } return false; }); $("body").bind("dragleave", function(e){ e.originalEvent.preventDefault(); console.log(e.type, e.target.id, e.originalEvent); console.log("next_dragleave_cancel: "+next_dragleave_cancel); if (next_dragleave_cancel) { next_dragleave_cancel = false; return false; } if ($(e.target).hasClass('area_fileupload_drop_here')) { $(".area_fileupload_drop").css("display", "none"); $(".area_fileupload").css("display", "block"); } return false; }); $(".area_fileupload_drop_here").bind("click", function(e) { $(".area_fileupload_drop").css("display", "none"); $(".area_fileupload").css("display", "block"); }); setTimeout(function(){ lock_uploadenable = true; }, 500); }); function genThumb(_config, _callback) { var promise_genthum; var _size = _config["file"].size; var _type = _config["file"].type; if (_size >= _config["size_min"] && _size <= _config["size_max"] && (_type.indexOf("image/png") != -1 || _type.indexOf("image/jpeg") != -1)) { promise_genthum = new Promise((resolve, reject) => { var reader = new FileReader(); reader.onload = function(){ var _img = new Image(); _img.onload = function() { try { if (_img.width <= _config["width"] && _img.height <= _config["height"]) { console.log("genThumb: skip: width or height"); resolve(); return; } var canvasAspect = _config["width"] / _config["height"], imgAspect = _img.width / _img.height, left, top, width, height; var _cvs = document.createElement("canvas"); _cvs.width = _config["width"]; _cvs.height = _config["height"]; _ctx = _cvs.getContext("2d"); _ctx.globalAlpha = 1; _ctx.fillStyle = "#ffffff"; //_ctx.fillStyle = "#ff0000"; _ctx.fillRect(0, 0, _config["width"], _config["height"]); if (imgAspect >= canvasAspect) { left = 0; width = _ctx.canvas.width; height = _ctx.canvas.width / imgAspect; top = (_ctx.canvas.height - height) / 2; } else { top = 0; height = _ctx.canvas.height; width = _ctx.canvas.height * imgAspect; left = (_ctx.canvas.width - width) / 2; } _ctx.drawImage(_img, 0, 0, _img.width, _img.height, left, top, width, height); resolve(_cvs.toDataURL("image/jpeg", 0.8)); return; } catch (e) { console.error("genThumb: ", e); resolve(); return; } }; _img.onerror = function(e) { console.error("genThumb: ", e); resolve(); return; }; _img.src = reader.result; }; reader.onerror = function(e){ console.error("genThumb: ", e); resolve(); return; } reader.readAsDataURL(_config["file"]); }); } Promise.all([promise_genthum]).then((_thumimg) => { _callback(_thumimg); }); }