layui-vue/es/upload/index.js
2023-11-03 11:48:11 +08:00

440 lines
23 KiB
JavaScript

import { w as withInstall } from "../badge/index2.js";
import { defineComponent, computed, useSlots, getCurrentInstance, watch, ref, onMounted, nextTick, onUnmounted, openBlock, createElementBlock, normalizeClass, createElementVNode, withModifiers, unref, renderSlot, createBlock, withCtx, createTextVNode, toDisplayString, createVNode, Fragment, renderList } from "vue";
import { a as _sfc_main$2, l as layer } from "../_chunks/@layui/index.js";
import { t as templateRef } from "../_chunks/@vueuse/index.js";
import { _ as _sfc_main$1 } from "../button/index2.js";
import { C as Cropper } from "../_chunks/cropperjs/index.js";
import { u as useI18n } from "../datePicker/index2.js";
import "../_chunks/dayjs/index.js";
import "../_chunks/@umijs/index.js";
import "../input/index2.js";
import "../dropdownMenu/index2.js";
import "../dropdown/index2.js";
import "../_chunks/vue-i18n/index.js";
import "../_chunks/@intlify/index.js";
import "../_chunks/@vue/index.js";
var index = /* @__PURE__ */ (() => '/*!\n * Cropper.js v1.5.12\n * https://fengyuanchen.github.io/cropperjs\n *\n * Copyright 2015-present Chen Fengyuan\n * Released under the MIT license\n *\n * Date: 2021-06-12T08:00:11.623Z\n */.cropper-container{direction:ltr;font-size:0;line-height:0;position:relative;-ms-touch-action:none;touch-action:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.cropper-container img{image-orientation:0deg;display:block;height:100%;max-height:none!important;max-width:none!important;min-height:0!important;min-width:0!important;width:100%}.cropper-canvas,.cropper-crop-box,.cropper-drag-box,.cropper-modal,.cropper-wrap-box{bottom:0;left:0;position:absolute;right:0;top:0}.cropper-canvas,.cropper-wrap-box{overflow:hidden}.cropper-drag-box{background-color:#fff;opacity:0}.cropper-modal{background-color:#000;opacity:.5}.cropper-view-box{display:block;height:100%;outline:1px solid #39f;outline-color:#3399ffbf;overflow:hidden;width:100%}.cropper-dashed{border:0 dashed #eee;display:block;opacity:.5;position:absolute}.cropper-dashed.dashed-h{border-bottom-width:1px;border-top-width:1px;height:33.33333%;left:0;top:33.33333%;width:100%}.cropper-dashed.dashed-v{border-left-width:1px;border-right-width:1px;height:100%;left:33.33333%;top:0;width:33.33333%}.cropper-center{display:block;height:0;left:50%;opacity:.75;position:absolute;top:50%;width:0}.cropper-center:after,.cropper-center:before{background-color:#eee;content:" ";display:block;position:absolute}.cropper-center:before{height:1px;left:-3px;top:0;width:7px}.cropper-center:after{height:7px;left:0;top:-3px;width:1px}.cropper-face,.cropper-line,.cropper-point{display:block;height:100%;opacity:.1;position:absolute;width:100%}.cropper-face{background-color:#fff;left:0;top:0}.cropper-line{background-color:#39f}.cropper-line.line-e{cursor:ew-resize;right:-3px;top:0;width:5px}.cropper-line.line-n{cursor:ns-resize;height:5px;left:0;top:-3px}.cropper-line.line-w{cursor:ew-resize;left:-3px;top:0;width:5px}.cropper-line.line-s{bottom:-3px;cursor:ns-resize;height:5px;left:0}.cropper-point{background-color:#39f;height:5px;opacity:.75;width:5px}.cropper-point.point-e{cursor:ew-resize;margin-top:-3px;right:-3px;top:50%}.cropper-point.point-n{cursor:ns-resize;left:50%;margin-left:-3px;top:-3px}.cropper-point.point-w{cursor:ew-resize;left:-3px;margin-top:-3px;top:50%}.cropper-point.point-s{bottom:-3px;cursor:s-resize;left:50%;margin-left:-3px}.cropper-point.point-ne{cursor:nesw-resize;right:-3px;top:-3px}.cropper-point.point-nw{cursor:nwse-resize;left:-3px;top:-3px}.cropper-point.point-sw{bottom:-3px;cursor:nesw-resize;left:-3px}.cropper-point.point-se{bottom:-3px;cursor:nwse-resize;height:20px;opacity:1;right:-3px;width:20px}@media (min-width:768px){.cropper-point.point-se{height:15px;width:15px}}@media (min-width:992px){.cropper-point.point-se{height:10px;width:10px}}@media (min-width:1200px){.cropper-point.point-se{height:5px;opacity:.75;width:5px}}.cropper-point.point-se:before{background-color:#39f;bottom:-50%;content:" ";display:block;height:200%;opacity:0;position:absolute;right:-50%;width:200%}.cropper-invisible{opacity:0}.cropper-bg{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC)}.cropper-hide{display:block;height:0;position:absolute;width:0}.cropper-hidden{display:none!important}.cropper-move{cursor:move}.cropper-crop{cursor:crosshair}.cropper-disabled .cropper-drag-box,.cropper-disabled .cropper-face,.cropper-disabled .cropper-line,.cropper-disabled .cropper-point{cursor:not-allowed}:root{--button-primary-text-color: #fff;--button-primary-background-color: var(--global-primary-color);--button-primary-border-color: var(--global-primary-color);--button-normal-text-color: #fff;--button-normal-background-color: var(--global-normal-color);--button-normal-border-color: var(--global-normal-color);--button-warm-text-color: #fff;--button-warm-background-color: var(--global-warm-color);--button-warm-border-color: var(--global-warm-color);--button-danger-text-color: #fff;--button-danger-background-color: var(--global-danger-color);--button-danger-border-color: var(--global-danger-color);--button-border-radius: var(--global-border-radius);--button-border-color: var(--global-neutral-color-6);--button-background-color: 0 0;--button-text-color: #666}.layui-btn{height:38px;line-height:36px;padding:0 18px;font-size:14px;text-align:center;white-space:nowrap;color:var(--button-text-color);background:var(--button-background-color);border-radius:var(--button-border-radius);border-color:var(--button-border-color);border-width:1px;border-style:solid;cursor:pointer}.layui-btn-primary{color:var(--button-primary-text-color);background-color:var(--button-primary-background-color);border-color:var(--button-primary-border-color)}.layui-btn-normal{color:var(--button-normal-text-color);background-color:var(--button-normal-background-color);border-color:var(--button-normal-border-color)}.layui-btn-warm{color:var(--button-warm-text-color);background-color:var(--button-warm-background-color);border-color:var(--button-warm-border-color)}.layui-btn-danger{color:var(--button-danger-text-color);background-color:var(--button-danger-background-color);border-color:var(--button-danger-border-color)}.layui-btn:hover{opacity:.8;filter:alpha(opacity=80)}.layui-btn:active{opacity:1;filter:alpha(opacity=100)}.layui-btn-lg{height:44px;line-height:44px;padding:0 25px;font-size:16px}.layui-btn-sm{height:30px;line-height:30px;padding:0 10px;font-size:12px}.layui-btn-xs{height:22px;line-height:22px;padding:0 5px;font-size:12px}.layui-btn-xs i{font-size:12px!important}.layui-btn-fluid{width:100%}.layui-btn-radius{border-radius:100px}.layui-btn-disabled,.layui-btn-disabled:active,.layui-btn-disabled:hover{border-color:#eee!important;background-color:#fbfbfb!important;color:#d2d2d2!important;cursor:not-allowed!important;opacity:1}.layui-btn+.layui-btn{margin-left:10px}.layui-btn .layui-icon{padding:0 2px;vertical-align:middle\\ ;vertical-align:bottom}.layui-upload-file{opacity:.01;position:relative;filter:alpha(opacity=1);cursor:pointer}.layui-upload-btn-box{position:relative;overflow:hidden}.layui-upload-drag,.layui-upload-form,.layui-upload-wrap{display:inline-block}.layui-upload-list{margin:10px 0}.layui-upload-choose{max-width:200px;padding:0 10px;color:#999;font-size:14px;text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.layui-upload-drag{position:relative;padding:30px;border:1px dashed var(--global-neutral-color-4);background-color:#fff;text-align:center;cursor:pointer;color:#999}.layui-upload-drag .layui-icon{font-size:50px;color:var(--global-primary-color)}.layui-upload-drag[lay-over],.layui-upload-drag-draging{border-color:var(--global-primary-color)}.layui-upload-iframe{position:absolute;width:0;height:0;border:0;visibility:hidden}.layui-upload-wrap{position:relative;vertical-align:middle;cursor:pointer}.layui-upload-wrap .layui-upload-file{display:block!important;position:absolute;left:0;top:0;z-index:10;font-size:100px;width:1px;height:1px;opacity:.01;filter:alpha(opacity=1)}.layui-upload-file-disabled{cursor:not-allowed!important}.layui-btn-container .layui-upload-choose{padding-left:0}.layui-upload-drag-disable{opacity:.8;z-index:1;cursor:not-allowed}._lay_upload_img{display:block;max-width:100%}.layui-upload-list-disabled{width:auto;height:auto;pointer-events:none!important;background-color:#fbfbfb!important;filter:opacity(.9)}\n')();
const _hoisted_1 = ["name", "field", "multiple", "accept", "disabled"];
const _hoisted_2 = { key: 0 };
const _hoisted_3 = ["onClick"];
const _hoisted_4 = ["onClick"];
const _hoisted_5 = /* @__PURE__ */ createElementVNode("i", { class: "layui-icon" }, "\uE67C", -1);
const _hoisted_6 = /* @__PURE__ */ createElementVNode("div", {
class: "layui-hide",
id: "uploadDemoView"
}, [
/* @__PURE__ */ createElementVNode("hr"),
/* @__PURE__ */ createElementVNode("img", {
src: "",
alt: "\u4E0A\u4F20\u6210\u529F\u540E\u6E32\u67D3",
style: { "max-width": "196px" }
})
], -1);
const _hoisted_7 = ["src", "id"];
const __default__ = {
name: "LayUpload"
};
const _sfc_main = defineComponent({
...__default__,
props: {
url: null,
data: null,
headers: null,
acceptMime: { default: "MIME_type" },
field: { default: "file" },
size: { default: 0 },
multiple: { type: Boolean, default: false },
number: { default: 0 },
drag: { type: Boolean, default: false },
disabled: { type: Boolean, default: false },
disabledPreview: { type: Boolean, default: false },
cut: { type: Boolean, default: false },
cutOptions: { default: void 0 },
text: null,
dragText: null,
modelValue: { default: null },
auto: { type: Boolean, default: true }
},
emits: [
"choose",
"chooseAfter",
"before",
"done",
"error",
"cutdone",
"cutcancel",
"update:modelValue"
],
setup(__props, { emit }) {
const props = __props;
const getCutDownResult = () => {
if (_cropper) {
const canvas = _cropper.getCroppedCanvas();
let imgData = canvas.toDataURL('"image/png"');
let currentTimeStamp = new Date().valueOf();
let orgInfo = activeUploadFiles.value[0];
emit("cutdone", Object.assign({ currentTimeStamp, cutResult: imgData, orginal: orgInfo }));
let newFile = dataURLtoFile(imgData);
if (!props.auto) {
emit("update:modelValue", [newFile]);
clearLightCutEffect();
return;
}
commonUploadTransaction([newFile]);
nextTick(() => clearAllCutEffect());
} else {
errorF(cutInitErrorMsg.value);
}
};
const closeCutDownModal = () => {
let currentTimeStamp = new Date().valueOf();
emit("cutcancel", Object.assign({ currentTimeStamp }));
nextTick(() => clearAllCutEffect());
};
const clearAllCutEffect = () => {
activeUploadFiles.value = [];
activeUploadFilesImgs.value = [];
innerCutVisible.value = false;
orgFileInput.value.value = "";
_cropper = null;
};
const clearLightCutEffect = () => {
activeUploadFiles.value = [];
activeUploadFilesImgs.value = [];
innerCutVisible.value = false;
_cropper = null;
};
const { t } = useI18n();
const text = computed(() => {
return props.text ? props.text : t("upload.text");
});
const dragText = computed(() => {
return props.dragText ? props.dragText : t("upload.dragText");
});
const defaultErrorMsg = computed(() => t("upload.defaultErrorMsg"));
const urlErrorMsg = computed(() => t("upload.urlErrorMsg"));
const numberErrorMsg = computed(() => t("upload.numberErrorMsg"));
const occurFileSizeErrorMsg = computed(() => t("upload.occurFileSizeErrorMsg"));
const cutInitErrorMsg = computed(() => t("upload.cutInitErrorMsg"));
const uploadSuccess = computed(() => t("upload.uploadSuccess"));
const startUploadMsg = computed(() => t("upload.startUploadMsg"));
const cannotSupportCutMsg = computed(() => t("upload.cannotSupportCutMsg"));
const title = computed(() => t("upload.title"));
const confirmBtn = computed(() => t("upload.confirmBtn"));
const cancelBtn = computed(() => t("upload.cancelBtn"));
let defaultCutLayerOption = computed(() => {
return {
type: "component",
title: title.value,
shade: true,
shadeClose: true,
area: ["640px", "640px"],
btn: [
{ text: confirmBtn.value, callback: getCutDownResult },
{ text: cancelBtn.value, callback: closeCutDownModal }
]
};
});
const slot = useSlots();
slot.default && slot.default();
getCurrentInstance();
watch(() => props.modelValue, () => {
if (!props.modelValue) {
clearAllCutEffect();
}
});
const isDragEnter = ref(false);
const activeUploadFiles = ref([]);
const activeUploadFilesImgs = ref([]);
const orgFileInput = templateRef("orgFileInput");
let _cropper = null;
let computedCutLayerOption;
if (props.cutOptions && props.cutOptions.layerOption) {
computedCutLayerOption = computed(() => Object.assign(defaultCutLayerOption, props.cutOptions.layerOption));
} else {
computedCutLayerOption = computed(() => defaultCutLayerOption.value);
}
const innerCutVisible = ref(false);
const localUploadTransaction = (option) => {
const { url, files } = option;
let formData = new FormData();
if (url.length <= 5) {
errorF(urlErrorMsg.value);
return;
}
if (Array.isArray(files) && files.length > 0) {
for (let i = 0; i < files.length; i++) {
let _file = files[i];
formData.append(props.field + "[" + i + "]", _file);
}
}
if (props.data && props.data instanceof Object) {
let _requestDate = props.data;
for (const key in _requestDate) {
formData.append(key, _requestDate[key]);
}
}
let utimer = window.setTimeout(() => {
localUpload({ url, formData }, function() {
clearTimeout(utimer);
});
}, 200);
};
const dataURLtoFile = (dataurl) => {
let arr = dataurl.split(",");
let mime = "";
if (arr.length > 0) {
mime = arr[0].match(/:(.*?);/)[1];
}
let bstr = atob(arr[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
};
const errorF = (errorText) => {
let currentTimeStamp = new Date().valueOf();
let errorMsg = errorText ? errorText : defaultErrorMsg;
errorMsg = `layui-vue:${errorMsg}`;
console.warn(errorMsg);
layer.msg(errorMsg, { icon: 2, time: 1e3 }, function(res) {
});
emit("error", Object.assign({ currentTimeStamp, msg: errorMsg }));
};
const localUpload = (option, callback) => {
let xhr = new XMLHttpRequest();
let url = option.url;
let formData = option.formData;
const cb = callback;
xhr.onreadystatechange = function() {
let currentTimeStamp2 = new Date().valueOf();
if (xhr.readyState === 1) {
if (xhr.status >= 200 && xhr.status <= 300 || xhr.status === 304 || xhr.status == 0) {
let successText = startUploadMsg.value;
emit("before", Object.assign({ currentTimeStamp: currentTimeStamp2, msg: successText, ...option }));
}
} else if (xhr.readyState === 4) {
let successText = xhr.responseText ? xhr.responseText : uploadSuccess;
if (xhr.status >= 200 && xhr.status <= 300 || xhr.status === 304 || xhr.status == 0) {
let data = xhr.responseText;
emit("done", { currentTimeStamp: currentTimeStamp2, msg: successText, data });
}
}
};
xhr.open("post", url, true);
if (props.headers) {
for (let key in props.headers) {
xhr.setRequestHeader(key, props.headers[key]);
}
} else {
xhr.setRequestHeader("Accept", "application/json, text/javascript");
}
let currentTimeStamp = new Date().valueOf();
emit("before", Object.assign(option, currentTimeStamp));
xhr.send(formData);
if (cb && typeof cb == "function") {
cb();
}
clearAllCutEffect();
};
const filetoDataURL = (file, fn) => {
const reader = new FileReader();
reader.onloadend = function(e) {
fn(e.target.result);
};
reader.readAsDataURL(file);
};
const uploadChange = (e) => {
e.preventDefault();
const _files = [...e.target.files || e.dataTransfer.files];
if (props.multiple && props.number != 0 && props.number < _files.length) {
errorF(numberErrorMsg.value);
return;
}
if (props.size && props.size != 0) {
for (let i = 0; i < _files.length; i++) {
let _file = _files[i];
let _size = _file.size;
if (_size > props.size * 1024) {
errorF(occurFileSizeErrorMsg.value);
return;
}
}
}
for (let item of _files) {
activeUploadFiles.value.push(item);
filetoDataURL(item, function(res) {
activeUploadFilesImgs.value.push(res);
});
}
let arm1 = props.cut && props.acceptMime.indexOf("image") != -1 && props.multiple == false;
let arm2 = props.cut && props.acceptMime.indexOf("image") != -1 && props.multiple == true;
if (arm1) {
innerCutVisible.value = true;
setTimeout(() => {
let _imgs = document.getElementsByClassName("_lay_upload_img");
if (_imgs && _imgs.length > 0) {
let _img = _imgs[0];
_cropper = new Cropper(_img, {
aspectRatio: 16 / 9
});
} else {
clearAllCutEffect();
}
}, 200);
} else {
if (arm2) {
console.warn(cannotSupportCutMsg.value);
}
if (!props.auto) {
emit("update:modelValue", _files);
return;
}
commonUploadTransaction(_files);
}
};
const commonUploadTransaction = (_files) => {
let currentTimeStamp = new Date().valueOf();
let successText = uploadSuccess;
if (props.url) {
localUploadTransaction({
url: props.url,
files: _files
});
} else {
emit("done", { currentTimeStamp, msg: successText, data: _files });
clearAllCutEffect();
}
};
const chooseFile = () => {
let _target = orgFileInput.value;
if (_target) {
_target.click();
}
};
const clickOrgInput = () => {
let currentTimeStamp = new Date().valueOf();
emit("choose", currentTimeStamp);
};
const dragRef = ref();
function dragEnter(e) {
e.stopPropagation();
e.preventDefault();
}
function dragOver(e) {
e.stopPropagation();
e.preventDefault();
}
onMounted(() => {
nextTick(() => {
if (dragRef.value) {
dragRef.value.addEventListener("dragenter", dragEnter, false);
dragRef.value.addEventListener("dragover", dragOver, false);
dragRef.value.addEventListener("drop", uploadChange, false);
}
});
});
onUnmounted(() => {
if (dragRef.value) {
dragRef.value.removeEventListener("dragenter");
dragRef.value.removeEventListener("dragover");
dragRef.value.removeEventListener("drop");
}
});
return (_ctx, _cache) => {
return openBlock(), createElementBlock("div", {
class: normalizeClass(["layui-upload layui-upload-wrap", __props.disabledPreview ? "layui-upload-file-disabled" : ""])
}, [
createElementVNode("input", {
type: "file",
class: "layui-upload-file",
ref_key: "orgFileInput",
ref: orgFileInput,
name: __props.field,
field: __props.field,
multiple: __props.multiple,
accept: __props.acceptMime,
disabled: __props.disabled,
onClick: clickOrgInput,
onChange: uploadChange
}, null, 40, _hoisted_1),
!__props.drag ? (openBlock(), createElementBlock("div", _hoisted_2, [
createElementVNode("div", {
class: "layui-upload-btn-box",
onClick: withModifiers(chooseFile, ["stop"])
}, [
unref(slot).default ? renderSlot(_ctx.$slots, "default", {
key: 0,
disabled: __props.disabled
}) : (openBlock(), createBlock(_sfc_main$1, {
key: 1,
type: "primary",
disabled: __props.disabled
}, {
default: withCtx(() => [
createTextVNode(toDisplayString(unref(text)), 1)
]),
_: 1
}, 8, ["disabled"]))
], 8, _hoisted_3)
])) : (openBlock(), createElementBlock("div", {
key: 1,
ref_key: "dragRef",
ref: dragRef,
class: normalizeClass([
"layui-upload-drag",
__props.disabled ? "layui-upload-drag-disable" : isDragEnter.value ? "layui-upload-drag-draging" : ""
]),
onClick: withModifiers(chooseFile, ["stop"])
}, [
_hoisted_5,
createElementVNode("p", null, toDisplayString(unref(dragText)), 1),
_hoisted_6
], 10, _hoisted_4)),
createVNode(unref(_sfc_main$2), {
modelValue: innerCutVisible.value,
"onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => innerCutVisible.value = $event),
title: unref(computedCutLayerOption).title,
move: unref(computedCutLayerOption).move,
resize: unref(computedCutLayerOption).resize,
shade: unref(computedCutLayerOption).shade,
shadeClose: unref(computedCutLayerOption).shadeClose,
shadeOpacity: unref(computedCutLayerOption).shadeOpacity,
zIndex: unref(computedCutLayerOption).zIndex,
btnAlign: unref(computedCutLayerOption).btnAlign,
area: unref(computedCutLayerOption).area,
anim: unref(computedCutLayerOption).anim,
isOutAnim: unref(computedCutLayerOption).isOutAnim,
btn: unref(computedCutLayerOption).btn,
onClose: clearAllCutEffect
}, {
default: withCtx(() => [
(openBlock(true), createElementBlock(Fragment, null, renderList(activeUploadFilesImgs.value, (base64str, index2) => {
return openBlock(), createElementBlock("div", {
class: "copper-container",
key: `file${index2}`
}, [
createElementVNode("img", {
src: base64str,
id: `_lay_upload_img${index2}`,
class: "_lay_upload_img"
}, null, 8, _hoisted_7)
]);
}), 128))
]),
_: 1
}, 8, ["modelValue", "title", "move", "resize", "shade", "shadeClose", "shadeOpacity", "zIndex", "btnAlign", "area", "anim", "isOutAnim", "btn"]),
createElementVNode("div", {
class: normalizeClass(["layui-upload-list", __props.disabledPreview ? "layui-upload-list-disabled" : ""])
}, [
renderSlot(_ctx.$slots, "preview")
], 2)
], 2);
};
}
});
const component = withInstall(_sfc_main);
export { component as default };