Files

235 lines
7.7 KiB
JavaScript

"use strict";
const common_vendor = require("../common/vendor.js");
const request_request = require("../request/request.js");
const request_api = require("../request/api.js");
const utils_watermark = require("./watermark.js");
const DEFAULT_QINIU_UPLOAD_URL = "https://upload.qiniup.com";
function getFileSuffix(filePath) {
var _a;
if (!filePath)
return "";
const clean = String(filePath).split("?")[0];
const ext = ((_a = clean.split(".").pop()) == null ? void 0 : _a.toLowerCase()) || "";
if (!ext || ext.length > 8 || clean.endsWith(ext) === false) {
return "jpg";
}
return ext;
}
function getFileMd5(filePath) {
return new Promise((resolve) => {
common_vendor.index.getFileInfo({
filePath,
digestAlgorithm: "md5",
success: (res) => resolve((res.digest || "").toLowerCase()),
fail: (err) => {
common_vendor.index.__f__("warn", "at utils/upload.js:32", "getFileMd5 fail, use empty:", err);
resolve("");
}
});
});
}
async function fetchQiniuUploadCredential(filePath) {
const suffix = getFileSuffix(filePath);
const fileMd5 = await getFileMd5(filePath);
const res = await request_api.getQiniuUploadToken({ fileMd5, suffix });
return normalizeQiniuCredential(res.data);
}
function normalizeQiniuCredential(raw) {
if (!raw) {
throw new Error("七牛凭证为空");
}
const token = raw.token || raw.uploadToken || raw.uptoken;
const key = raw.key || raw.fileKey || raw.objectKey;
const uploadUrl = (raw.uploadUrl || raw.uploadHost || raw.host || DEFAULT_QINIU_UPLOAD_URL).replace(/\/$/, "");
const presetUrl = String(raw.url || raw.fileUrl || raw.fullUrl || "").trim();
let cdnOrigin = (raw.domain || raw.cdnDomain || "").replace(/\/$/, "");
if (!cdnOrigin && presetUrl) {
const m = presetUrl.match(/^(https?:\/\/[^/]+)/i);
if (m)
cdnOrigin = m[1];
}
if (cdnOrigin && !cdnOrigin.startsWith("http")) {
cdnOrigin = `https://${cdnOrigin}`;
}
if (!token || !key) {
throw new Error("七牛凭证缺少 token 或 key");
}
return { token, key, uploadUrl, cdnOrigin, presetUrl };
}
function resolveUploadedFileUrl(credential, uploadResData) {
if (credential.presetUrl) {
return credential.presetUrl;
}
let objectKey = credential.key;
if (uploadResData) {
try {
const body = typeof uploadResData === "string" ? JSON.parse(uploadResData) : uploadResData;
if (body == null ? void 0 : body.key) {
objectKey = body.key;
}
} catch (e) {
}
}
if (credential.cdnOrigin && objectKey) {
return `${credential.cdnOrigin}/${String(objectKey).replace(/^\//, "")}`;
}
return buildQiniuFileUrl(credential.cdnOrigin, objectKey);
}
function buildQiniuFileUrl(domain, key) {
if (!domain || !key)
return "";
const k = String(key).replace(/^\//, "");
const d = String(domain).replace(/\/$/, "");
if (d.startsWith("http://") || d.startsWith("https://")) {
return `${d}/${k}`;
}
return `https://${d}/${k}`;
}
async function uploadToCloud(filePath, options = {}) {
let localPath = filePath;
if (options.beforeUpload) {
localPath = await options.beforeUpload(filePath);
}
const credential = await fetchQiniuUploadCredential(localPath);
const { token, key, uploadUrl } = credential;
return new Promise((resolve, reject) => {
common_vendor.index.uploadFile({
url: uploadUrl,
filePath: localPath,
name: "file",
formData: {
token,
key
},
success: (res) => {
if (res.statusCode && res.statusCode >= 400) {
reject(new Error(`七牛上传失败(${res.statusCode})`));
return;
}
const fullUrl = resolveUploadedFileUrl(credential, res.data);
if (!fullUrl) {
reject(new Error("无法解析上传后的文件地址,请检查后端 url 或 CDN 配置"));
return;
}
let respKey = key;
try {
const body = typeof res.data === "string" ? JSON.parse(res.data) : res.data;
if (body == null ? void 0 : body.key)
respKey = body.key;
} catch (e) {
}
resolve({
url: fullUrl,
key: respKey,
filePath: fullUrl,
serverPath: fullUrl
});
},
fail: (err) => {
common_vendor.index.__f__("error", "at utils/upload.js:167", "七牛上传失败:", err);
reject(err);
}
});
});
}
function toSubmitFileUrl(filePath) {
if (!filePath)
return "";
const p = String(filePath);
if (p.startsWith("http://") || p.startsWith("https://")) {
return p;
}
return request_request.toImageUrl(p);
}
function mapServerFileToUploadItem(att) {
const filePath = toSubmitFileUrl(att.filePath || att.url || "");
return {
url: filePath,
serverPath: filePath,
status: "success",
message: "",
name: att.fileName || att.name || "",
type: att.fileType || "image/jpeg",
size: att.fileSize || 0
};
}
function buildAttachmentItem(file, defaults = {}) {
var _a;
const filePath = toSubmitFileUrl(
file.serverPath || file.filePath || file.url || ""
);
const fileName = file.name || (filePath ? (_a = filePath.split("/").pop()) == null ? void 0 : _a.split("?")[0] : "") || "";
return {
fileName: fileName || defaults.fileName || "",
filePath,
fileType: file.type || defaults.fileType || "image/jpeg",
fileSize: file.size || defaults.fileSize || 0
};
}
function createUploadListHandlers(fileListRef, options = {}) {
const deletePic = (event) => {
fileListRef.value.splice(event.index, 1);
};
const afterRead = async (event) => {
const lists = [].concat(event.file);
let fileListLen = fileListRef.value.length;
lists.forEach((item) => {
fileListRef.value.push({
...item,
status: "uploading",
message: "上传中"
});
});
for (let i = 0; i < lists.length; i++) {
const listIndex = fileListLen;
try {
const beforeUpload = options.watermark ? (tempFilePath) => utils_watermark.addTimestampWatermark({
tempFilePath,
...options.watermark
}) : void 0;
const result = await uploadToCloud(lists[i].url, { beforeUpload });
const item = fileListRef.value[listIndex];
fileListRef.value.splice(listIndex, 1, {
...item,
status: "success",
message: "",
url: result.url,
serverPath: result.url
});
} catch (e) {
common_vendor.index.__f__("error", "at utils/upload.js:263", "上传失败:", e);
const item = fileListRef.value[listIndex];
fileListRef.value.splice(listIndex, 1, {
...item,
status: "failed",
message: (e == null ? void 0 : e.msg) || (e == null ? void 0 : e.message) || "上传失败"
});
common_vendor.index.showToast({
title: (e == null ? void 0 : e.msg) || (e == null ? void 0 : e.message) || "上传失败",
icon: "none"
});
}
fileListLen++;
}
};
return { afterRead, deletePic };
}
function uploadSingleWithLoading(filePath, options = {}) {
const loadingTitle = options.loadingTitle || "上传中...";
common_vendor.index.showLoading({ title: loadingTitle, mask: true });
return uploadToCloud(filePath, options).then((result) => {
common_vendor.index.hideLoading();
return result;
}).catch((err) => {
common_vendor.index.hideLoading();
throw err;
});
}
exports.buildAttachmentItem = buildAttachmentItem;
exports.createUploadListHandlers = createUploadListHandlers;
exports.mapServerFileToUploadItem = mapServerFileToUploadItem;
exports.toSubmitFileUrl = toSubmitFileUrl;
exports.uploadSingleWithLoading = uploadSingleWithLoading;
exports.uploadToCloud = uploadToCloud;
//# sourceMappingURL=../../.sourcemap/mp-weixin/utils/upload.js.map