修改上傳圖片套件

This commit is contained in:
dev02 2022-12-09 15:37:15 +08:00
parent 98031df604
commit 95843906fd
4 changed files with 232 additions and 112 deletions

View File

@ -92,7 +92,7 @@
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="inpFixDoCode">維修項目代碼(設備編號)</label>
<select class="form-control" id="inpFixDoCode" name="inpFixDoCode" disabled>
<select class="form-control" id="inpFixDoCode" name="inpFixDoCode">
<option value=''>未選擇</option>
</select>
</div>
@ -143,9 +143,14 @@
<textarea class="form-control" type="text" id="inpDescription" name="inpDescription" rows="7"></textarea>
</div>
</div>
<div class="col-md-12 dropzone-container">
<div class="col-md-12">
<label class="form-label">上傳檔案</label>
<div class="form-group dropzone" id="frmFileUpload">
<div id='alr_forImage' class="col-sm-12 forimage mt-2 p-0">
</div>
<div id='alr_forFile' class="col-sm-12 forfile mt-2 p-0">
</div>
<div class="form-group dropzone" id="alr_dropZone">
<div class="dz-message">
<div class="drag-icon-cph">
<i class="material-icons">backup</i>
@ -158,11 +163,6 @@
<div class="fallback">
<input name="file" type="file" multiple />
</div>
<!--<label for="myImage" class="file-upload" style="cursor : pointer ">點擊上傳檔案</label>
<input id="myImage" class="form-control dropzone" type="file" multiple hidden />-->
</div>
<div id='forImage' class="col-sm-12 forimage mt-2 p-0">
</div>
</div>
</div>
@ -181,10 +181,11 @@
pageAct.selSysSub = null;
pageAct.alr_startdate = null;
pageAct.alr_enddate = null;
pageAct.imageFile = [];
first = true;
$(function () {
$(loadEle).Loading("close");
initDropzone();
setReturn(false);
setConfirm(false);
event();
@ -287,10 +288,15 @@
+ alr_tableData.alarmClass.toString().split('_')[1] + "_" + alr_tableData.buildingFloorName_zh.toString().split('-')[1] + "_" + alr_tableData.sourceName_zh.toString().split('-')[0] + "_"
+ alr_tableData.sourceName_zh.toString().split('-')[1];
$('#inpFixDoCode').val($(`option[value*=${deviceNumber}]`).val() !== undefined ? $(`option[value*=${deviceNumber}]`).val() : "");
selUser();
selDevice();
selOpeFir();
$('#inpFixDoCode option[data-sub=' + alr_tableData.alarmClass.toString().split('_')[1] + '][data-main=' + alr_tableData.alarmClass.toString().split('_')[0] + ']').attr('hidden', false);
$('#inpFixDoCode option[data-sub!=' + alr_tableData.alarmClass.toString().split('_')[1] + '][data-main!=' + alr_tableData.alarmClass.toString().split('_')[0] + ']').attr('hidden', true);
let alr_fixDoCode = $($('#inpFixDoCode option[data-sub=' + alr_tableData.alarmClass.toString().split('_')[1] + '][data-main=' + alr_tableData.alarmClass.toString().split('_')[0] + ']')[0]).val();
$('#inpFixDoCode').val(alr_fixDoCode);
});
}
@ -486,7 +492,7 @@
"title": "異常類別",
"data": "alarmClass",
"render": function (data) {
return data.split('_')[1];
return data.split('_')[0] + "-" + data.split('_')[1];
}
},
{
@ -550,7 +556,7 @@
strHtml = ``;
$("#inpFixDoCode").html();
$.each(res.data, (index, roleObj) => {
strHtml += `<option value='${roleObj.device_number}' data-floor=${roleObj.device_floor_tag} data-main=${roleObj.device_system_tag} data-sub=${roleObj.device_name_tag}>${roleObj.device_name}</option>`;
strHtml += `<option value='${roleObj.device_number}' data-floor=${roleObj.device_floor_tag} data-main=${roleObj.device_system_tag} data-sub=${roleObj.device_name_tag} hidden>${roleObj.device_name}</option>`;
if (index == 0) {
pageAct.sysMain = roleObj.device_system_tag;
@ -598,4 +604,49 @@
}
}, null, "POST").send();
}
//上傳檔案 dropzone
function initDropzone() {
uploader = $("#alr_dropZone").dropzone({
url: baseApiUrl + '/api/Upload',
previewsContainer: false,
addRemoveLinks: false,
dictRemoveFile: `<span class="material-icons mi-delete">delete</span>`,
dictInvalidFileType: `上傳格式錯誤`,
dictCancelUploadConfirmation: `確定要取消上傳此檔案嗎?`,
dictCancelUpload: `<span class="material-icons mi-cancel">cancel</span>`,
maxFilesize: 3,
filesizeBase: 1024,
maxFiles: 50,
acceptedFiles: ".pdf, .docx, .doc, .xls, .xlsm, .xlsx, .ppt, .pptx, .gif, .png, .jpg, .jpeg",
headers: { "Authorization": 'Bearer ' + localStorage.getItem("JWT-Authorization") },
accept: function (file, done) {
let fileHelper = new YourTeam.Utility.File();
tmpGuidArr = [];
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
fileHelper.readAndPreviewImages(file, 'alr_forImage', 70, 70, '<span class="file-item m-1">', '<button class="btn-dark m-1" name="btnDelImg"><i class="fa fa-times"></i></button></span>');
pageAct.imageFile.map(function (v, i) { tmpGuidArr.push(v.file.guid) });
if (jQuery.inArray(file.guid, tmpGuidArr) == -1) { //not in array
let fd = new FormData();
let f = file;
fd.append('file', f);
pageAct.imageFile.push({ "ori_file_name": f.name, "save_file_name": f.guid, "file": fd.get("file") });
}
}
else if (/\.(xls?x|doc?x|ptt?x|pdf|zip|rar|7zip|txt|odt|xml|rtf|ods|odp|pps?x)$/i.test(file.name)) {
fileHelper.readAndPreviewFiles(file, 'alr_forFile', 70, 70, "<div class='file-item'><i class='fas fa-file-alt fa-2x m-1'></i>", "<button class='btn-dark m-1' name='btnDelImg'><i class='fa fa-times'></i></button></div>");
pageAct.imageFile.map(function (v, i) { tmpGuidArr.push(v.file.guid) });
if (jQuery.inArray(file.guid, tmpGuidArr) == -1) { //not in array
let fd = new FormData();
let f = file;
fd.append('file', f);
pageAct.imageFile.push({ "ori_file_name": f.name, "save_file_name": f.guid, "file": fd.get("file") });
}
}
}
});
}
</script>

View File

@ -7,7 +7,7 @@
<div class="col-auto">
<div class="btn-group">
<button type="button" onclick="setType(2)" class="btn btn-secondary waves-effect waves-themed">維修</button>
<button type="button" onclick="setType(1)" class="btn btn-secondary waves-effect waves-themed">記錄</button>
<button type="button" onclick="setType(1)" class="btn btn-secondary waves-effect waves-themed">記錄</button>
<button type="button" onclick="setType(null)" class="btn btn-secondary waves-effect waves-themed">廠商資料</button>
</div>
</div>
@ -246,9 +246,14 @@
<textarea class="form-control" type="text" id="inpDescription" name="inpDescription" rows="7"></textarea>
</div>
</div>
<div class="col-md-12 dropzone-container">
<div class="col-md-12">
<label class="form-label">上傳檔案</label>
<div class="form-group dropzone" id="frmFileUpload">
<div id='ope_forImage' class="col-sm-12 forimage mt-2 p-0">
</div>
<div id='ope_forFile' class="col-sm-12 forfile mt-2 p-0">
</div>
<div class="form-group dropzone" id="ope_dropZone">
<div class="dz-message">
<div class="drag-icon-cph">
<i class="material-icons">backup</i>
@ -261,11 +266,6 @@
<div class="fallback">
<input name="file" type="file" multiple />
</div>
<!--<label for="myImage" class="file-upload" style="cursor : pointer ">點擊上傳檔案</label>
<input id="myImage" class="form-control dropzone" type="file" multiple hidden />-->
</div>
<div id='forImage' class="col-sm-12 forimage mt-2 p-0">
</div>
</div>
</div>
@ -301,10 +301,13 @@
<script>
$(function () {
$(loadEle).Loading("close");
initDropzone();
pageAct.sub_system_tag = null;
pageAct.main_system_tag = null;
pageAct.selSysSub = [];
pageAct.selSysMain = [];
pageAct.imageFile = [];
sysList();
@ -1071,34 +1074,6 @@
}, null, "POST").send()
});
onEvent("change", "#myImage", function (e) {
var imageuploadFormOS = 0;
let fileHelper = new YourTeam.Utility.File();
//若有文字顯示,清除文字顯示
if ($('#forImage p').length > 0) {
$("#forImage").html(""); // 清除預覽
}
//console.log(this.files)
imageuploadFormOS = this.files.length;
//最多只能上傳幾張
let maxlength = $("#forImage").data("maxlength");
if (maxlength) {
if (imageuploadFormOS + $('#forImage img').length > maxlength) {
ShowModal("error", "uplImgOverLen", "無法上傳", "最多只能上傳" + maxlength + "張,您已經超出上傳數量。");
$("#myImage").val("");
return false;
}
}
if (/\.(jpe?g|png|gif)$/i.test(this.file.name))
fileHelper.readAndPreviewImages(this.files, 'forImage', 150, 70, '<div class="file-item">', '<button class="btn-info" name="btnDelImg" ><i class="fa fa-times"></i></button></div>');
$.each(this.files, function (i, v) {
let fd = new FormData();
let file = v;
fd.append('file', v);
pageAct.imageFile.push({ "ori_file_name": v.name, "save_file_name": file.guid, "file": fd.get("file") });
});
}); //變更圖片
onEvent("click", "[name=btnDelImg]", function () {
elem = $(this).parent();
if (elem.attr('data-id'))
@ -1108,6 +1083,11 @@
$.grep(pageAct.imageFile, function (image) {
return image.save_file_name != elem.find('img').data('savename');
});
pageAct.imageFile =
$.grep(pageAct.imageFile, function (file) {
return file.save_file_name != elem.find('a').data('savename');
});
}
elem.remove();
@ -1130,7 +1110,6 @@
selOpeFir();
errCodeList();
});
}
function errCodeList() {
@ -1157,61 +1136,46 @@
//上傳檔案 dropzone
function initDropzone() {
let avaUplFilsArr = $("#frmFileUpload").parents(".update").data("avauplfil");
let uploadedFilesNameArr = [];
uploader = $("#frmFileUpload").dropzone({
addRemoveLinks: true,
uploader = $("#ope_dropZone").dropzone({
url: baseApiUrl + '/api/Upload',
previewsContainer: false,
addRemoveLinks: false,
dictRemoveFile: `<span class="material-icons mi-delete">delete</span>`,
dictInvalidFileType: `上傳格式錯誤`,
dictCancelUploadConfirmation: `確定要取消上傳此檔案嗎?`,
dictCancelUpload: `<span class="material-icons mi-cancel">cancel</span>`,
maxFilesize: 3,
filesizeBase: 1024,
maxFiles: 5,
acceptedFiles: ".pdf, .docx, .doc, .xls, .xlsm, .xlsx, .ppt, .pptx",
maxFiles: 50,
acceptedFiles: ".pdf, .docx, .doc, .xls, .xlsm, .xlsx, .ppt, .pptx, .gif, .png, .jpg, .jpeg",
headers: { "Authorization": 'Bearer ' + localStorage.getItem("JWT-Authorization") },
accept: function (file, done) {
let fileHelper = new YourTeam.Utility.File();
tmpGuidArr = [];
if (avaUplFilsArr.findIndex(x => x.split(".")[0] == file.name.split(".")[0]) == -1) {
done("只能上傳諮詢師指派給您的相關檔案。");
} else if (uplFiles.findIndex(x => x.name == file.name) != -1) {
done("只能上傳一筆同檔名檔案。");
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
fileHelper.readAndPreviewImages(file, 'ope_forImage', 70, 70, '<span class="file-item m-1">', '<button class="btn-dark m-1" name="btnDelImg"><i class="fa fa-times"></i></button></span>');
pageAct.imageFile.map(function (v, i) { tmpGuidArr.push(v.file.guid) });
if (jQuery.inArray(file.guid, tmpGuidArr) == -1) { //not in array
let fd = new FormData();
let f = file;
fd.append('file', f);
pageAct.imageFile.push({ "ori_file_name": f.name, "save_file_name": f.guid, "file": fd.get("file") });
}
}
else { done(); }
else if (/\.(xls?x|doc?x|ptt?x|pdf|zip|rar|7zip|txt|odt|xml|rtf|ods|odp|pps?x)$/i.test(file.name)) {
fileHelper.readAndPreviewFiles(file, 'ope_forFile', 70, 70, "<div class='file-item'><i class='fas fa-file-alt fa-2x m-1'></i>", "<button class='btn-dark m-1' name='btnDelImg'><i class='fa fa-times'></i></button></div>");
pageAct.imageFile.map(function (v, i) { tmpGuidArr.push(v.file.guid) });
if (jQuery.inArray(file.guid, tmpGuidArr) == -1) { //not in array
let fd = new FormData();
let f = file;
fd.append('file', f);
pageAct.imageFile.push({ "ori_file_name": f.name, "save_file_name": f.guid, "file": fd.get("file") });
}
}
}
});
uploader[0].dropzone.on("addedfile", file => {
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = function (event) {
file.dataUrl = event.target.result;
};
})
uploader[0].dropzone.on("success", file => {
let strHtml = ``;
strHtml += `<li class="d-flex align-items-center py-2 px-3" data-uuid="${file.upload.uuid}">
<div><i class="material-icons">cloud_done</i></div>
<div class="d-flex justify-content-between align-items-center p-2 flex-fill">
<span>${file.upload.filename}</span>
<span>${convertSize(file.upload.total)}</span>
</div>
</li>`;
$(".update_box ul").append(strHtml);
$("#uploadBtnGro").show();
uplFiles.push(file);
uploadBtnGro();
})
uploader[0].dropzone.on("removedfile", file => {
$(`[data-uuid='${file.upload.uuid}']`).remove();
if (uplFiles.findIndex(x => x.upload.uuid == file.upload.uuid) != -1) {
uplFiles.splice(uplFiles.findIndex(x => x.upload.uuid == file.upload.uuid), 1);
}
uploadBtnGro();
})
}
</script>

View File

@ -492,8 +492,55 @@ class File {
let myFile = new YourTeam.Utility.File();
let strExtName = "", strOrgName = "";
for (let i = 0; i < files.length; i++) {
let file = files[i];
if (files.length > 0) {
for (let i = 0; i < files.length; i++) {
let file = files[i];
if (limitMaxSize != null) {
if (file.size / 1024 < limitMinSize || file.size / 1024 > limitMaxSize) {
limitFun ? limitFun() : "";
return false
}
}
htmlImg = "";
let guid = myMath.guid().replace(' ', '');
file.guid = guid;
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
let reader = new FileReader();
reader.addEventListener("load", function () {
let image = new Image();
let src = this.result;
image.src = this.result;
image.onload = function () {
strExtName = myFile.getFileExtension(file.name);
strOrgName = (strExtName === null || strExtName === "") ? file.name : file.name.replace('.' + strExtName, '');
htmlImg = frontHtml + '<img data-filename="' + file.name + '" data-orgname="' + strOrgName + '" data-savename="' + guid + '" data-extname="' + strExtName
+ '" data-size="' + file.size + '" width="' + width + '" height="' + height + '" src="' + src + '">'
+ backHtml;
container.insertAdjacentHTML("afterBegin", htmlImg);
//$("[name=" + removeClickTagName + "]").on("click", function (e) {
// e.preventDefault();
// $(this).closest(removeTag).remove();
//});
if (i === files.length - 1 && funDoSomeThing) {
funDoSomeThing();
}
}
});
reader.readAsDataURL(file);
} else {
if (showAlert) {
showAlert("danger", "只支援圖片格式");
}
else {
alert("只支援圖片格式");
}
}
}
}
else {
let file = files;
if (limitMaxSize != null) {
if (file.size / 1024 < limitMinSize || file.size / 1024 > limitMaxSize) {
limitFun ? limitFun() : "";
@ -504,7 +551,6 @@ class File {
let guid = myMath.guid().replace(' ', '');
file.guid = guid;
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
let reader = new FileReader();
reader.addEventListener("load", function () {
let image = new Image();
@ -522,7 +568,7 @@ class File {
// e.preventDefault();
// $(this).closest(removeTag).remove();
//});
if (i === files.length - 1 && funDoSomeThing) {
if (funDoSomeThing) {
funDoSomeThing();
}
}
@ -536,7 +582,7 @@ class File {
alert("只支援圖片格式");
}
}
}
}
}
readAndPreviewFiles(files, containerId, imgWidth = null, imgHeight = null, frontHtml = null, backHtml = null, funDoSomeThing = null) {
@ -548,31 +594,76 @@ class File {
let myFile = new YourTeam.Utility.File();
let strExtName = "", strOrgName = "", strSaveName = "";
for (let i = 0; i < files.length; i++) {
let file = files[i];
if (files.length) {
for (let i = 0; i < files.length; i++) {
let file = files[i];
htmlImg = "";
let guid = myMath.guid().replace(' ', '');
file.guid = guid;
//alert(/\.(xls?x|doc?x|ptt?x|pdf|zip|rar|7zip|txt|odt|xml|rtf|ods|odp|pps?x)$/i.test(file.name));
if (/\.(xls?x|doc?x|ptt?x|pdf|zip|rar|7zip|txt|odt|xml|rtf|ods|odp|pps?x)$/i.test(file.name)) {
if (file.size == 0) { //檔案大小為0時不會產生base64需防呆
showAlert("danger", "無法上傳大小為0的檔案");
return false;
}
//先新增a標籤 在套上src 可能解決多檔案上傳時無法讀取到最後上傳檔案的問題
strSaveName = guid;
strExtName = myFile.getFileExtension(file.name);
strOrgName = (strExtName === null || strExtName === "") ? file.name : file.name.replace('.' + strExtName, '');
htmlImg = frontHtml + '<a id="' + strSaveName + '" data-filename="' + file.name + '" data-orgname="' + strOrgName + '" data-savename="' + strSaveName + '" data-extname="' + strExtName
+ '" data-size="' + file.size + '" width="' + width + '" height="' + height + '" download="' + strOrgName + '.' + strExtName + '" target="_blank">' + strOrgName + '.' + strExtName + '</a>'
+ backHtml;
container.insertAdjacentHTML("afterBegin", htmlImg);
let reader = new FileReader();
reader.addEventListener("load", function (event) {
$($(container).find("a")[i]).attr("href", this.result);
if (i === files.length - 1 && funDoSomeThing) {
funDoSomeThing();
}
});
reader.readAsDataURL(file);
} else {
if (showAlert) {
showAlert("danger", "只支援文件格式");
} else {
alert("只支援文件格式");
}
}
}
}
else {
let file = files;
htmlImg = "";
let guid = myMath.guid().replace(' ', '');
file.guid = guid;
//alert(/\.(xls?x|doc?x|ptt?x|pdf|zip|rar|7zip|txt|odt|xml|rtf|ods|odp|pps?x)$/i.test(file.name));
if (/\.(xls?x|doc?x|ptt?x|pdf|zip|rar|7zip|txt|odt|xml|rtf|ods|odp|pps?x)$/i.test(file.name)) {
if (file.size == 0) { //檔案大小為0時不會產生base64需防呆
showAlert("danger", "無法上傳大小為0的檔案");
return false;
}
//先新增a標籤 在套上src 可能解決多檔案上傳時無法讀取到最後上傳檔案的問題
strSaveName = myMath.guid().replace(' ', '');
strSaveName = guid;
strExtName = myFile.getFileExtension(file.name);
strOrgName = (strExtName === null || strExtName === "") ? file.name : file.name.replace('.' + strExtName, '');
htmlImg = frontHtml + '<a id="' + strSaveName +'" data-filename="' + file.name + '" data-orgname="' + strOrgName + '" data-savename="' + strSaveName + '" data-extname="' + strExtName
+ '" data-size="' + file.size + '" width="' + width + '" height="' + height +'" download="' + strOrgName + '.' + strExtName + '" target="_blank">' + strOrgName + '.' + strExtName + '</a>'
htmlImg = frontHtml + '<a id="' + strSaveName + '" data-filename="' + file.name + '" data-orgname="' + strOrgName + '" data-savename="' + strSaveName + '" data-extname="' + strExtName
+ '" data-size="' + file.size + '" width="' + width + '" height="' + height + '" download="' + strOrgName + '.' + strExtName + '" target="_blank">' + strOrgName + '.' + strExtName + '</a>'
+ backHtml;
container.insertAdjacentHTML("afterBegin", htmlImg);
let reader = new FileReader();
reader.addEventListener("load", function (event) {
$($(container).find("a")[i]).attr("href", this.result);
if (i === files.length - 1 && funDoSomeThing) {
$($(container).find("a")).attr("href", this.result);
if (funDoSomeThing) {
funDoSomeThing();
}
});
@ -585,7 +676,7 @@ class File {
alert("只支援文件格式");
}
}
}
}
}
async getBase64Image(path, callback) {
//生成canvas

View File

@ -1,8 +1,10 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using Repository.BackendRepository.Interface;
using Repository.FrontendRepository.Interface;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Net;
@ -76,5 +78,17 @@ namespace FrontendWebApi.ApiControllers
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "excel", path);
return File(System.IO.File.ReadAllBytes(Path.Combine(filePath, fileName)), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
}
[HttpPost]
[Route("api/Upload")]
public ActionResult DroZonUplFile()
{
var a = HttpContext.Request.Form.Files;
return Json(new
{
code = "0000",
data = HttpContext.Request.Form.Files
});
}
}
}