tiefen_space_h5/utils/upload.js

290 lines
7.4 KiB
JavaScript
Raw Normal View History

2024-07-02 15:09:48 +08:00
"use client";
import baseRequest from "./baseRequest";
import CryptoJS from "crypto-js";
import { Toast } from "antd-mobile";
import { generateSignature } from "@/utils/crypto";
//获取auth
async function getAuth(mtype) {
const base = baseRequest();
const signature = generateSignature({
mtype: mtype,
...base,
});
try {
const response = await fetch(`/api/media/auth?signature=${signature}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
mtype: mtype,
...base,
}),
});
const data = await response.json();
if (data.ret === -1) {
Toast.show({
content: data.msg,
});
return;
}
return data.data.policy_token;
} catch (error) {
console.error(error);
}
}
//计算媒体参数
async function calculateFileMetadata(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event) => {
try {
const fileData = event.target.result;
const wordArray = CryptoJS.lib.WordArray.create(fileData);
const md5Hash = CryptoJS.MD5(wordArray).toString();
const mediaElement = document.createElement(
file.type.startsWith("image/") ? "img" : "video"
);
mediaElement.src = URL.createObjectURL(file);
mediaElement.addEventListener(
file.type.startsWith("image/") ? "load" : "loadedmetadata",
() => {
const metadata = {
md5Hash,
width: mediaElement.width || 0,
height: mediaElement.height || 0,
duration: mediaElement.duration || 0,
};
resolve(metadata);
}
);
mediaElement.addEventListener("error", () => {
const metadata = {
md5Hash,
width: 0,
height: 0,
duration: 0,
};
resolve(metadata);
});
} catch (error) {
reject(error);
}
};
reader.onerror = (error) => {
reject(error);
};
2024-07-10 00:48:37 +08:00
file.type?.startsWith("image/")
2024-07-02 15:09:48 +08:00
? reader.readAsDataURL(file)
: reader.readAsArrayBuffer(file);
});
}
2024-07-16 20:20:12 +08:00
//获取上传失败时返回的id
async function getFailId() {
const base = await baseRequest();
const signature = await generateSignature({
...base,
});
try {
const response = await fetch(
`/api/upload_media_fail_config/list?signature=${signature}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
...base,
}),
}
);
const data = await response.json();
if (data.ret === -1) {
Toast.show({
type: "error",
text1: data.msg,
topOffset: 60,
});
return;
}
return data.data;
} catch (e) {
console.warn(e);
}
}
2024-07-02 15:09:48 +08:00
//上传单张图片
export async function uploadImage(asset) {
const auth = await getAuth(1);
2024-08-05 18:59:30 +08:00
// console.log("auth", auth);
2024-07-02 15:09:48 +08:00
try {
const formData = new FormData();
formData.append("name", auth.filename);
formData.append("policy", auth.policy);
formData.append("OSSAccessKeyId", auth.access_key_id);
formData.append("success_action_status", "200");
formData.append("signature", auth.signature);
formData.append("key", auth.directory + "/" + auth.filename);
formData.append("file", asset);
2024-08-05 18:59:30 +08:00
// console.log("formData", ...formData);
2024-07-02 15:09:48 +08:00
const uploadResponse = await fetch(auth.host, {
method: "POST",
body: formData,
});
2024-08-05 18:59:30 +08:00
// console.log("uploadResponse", uploadResponse);
2024-07-02 15:09:48 +08:00
if (uploadResponse.status === 200) {
2024-07-15 20:00:44 +08:00
// console.log(asset);
// debugger
2024-07-02 15:09:48 +08:00
const info = await calculateFileMetadata(asset);
const item = {
src_id: auth.directory + "/" + auth.filename,
md5: info.md5Hash,
h: info.height,
w: info.width,
fmt: asset.type,
};
2024-07-16 20:20:12 +08:00
2024-07-02 15:09:48 +08:00
const base = baseRequest();
2024-08-05 18:34:44 +08:00
const response = await fetch(`/api/media/c_upload`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
mtype: 1,
item: item,
...base,
}),
});
2024-07-02 15:09:48 +08:00
const data = await response.json();
if (data.ret === -1) {
Toast.show({
content: data.msg,
});
return;
}
2024-08-02 22:12:54 +08:00
return data.data.ret_item.id;
2024-07-02 15:09:48 +08:00
} else {
Toast.show({
content: "上传图片失败",
});
}
} catch (error) {
2024-08-05 18:59:30 +08:00
// console.log("Error occurred while getting or uploading data:", error);
2024-07-02 15:09:48 +08:00
}
}
2024-07-16 20:20:12 +08:00
//上传单个视频
export async function uploadVideo(asset) {
const auth = await getAuth(2);
2024-07-17 16:58:27 +08:00
const fileType = asset?.type;
2024-07-16 20:20:12 +08:00
const generateThumbnail = async () => {
try {
const videoCover = await VideoThumbnails.getThumbnailAsync(asset?.uri);
return videoCover;
} catch (e) {
console.warn(e);
}
};
try {
const formData = new FormData();
formData.append("name", auth.filename);
formData.append("policy", auth.policy);
formData.append("OSSAccessKeyId", auth.access_key_id);
formData.append("success_action_status", "200");
formData.append("signature", auth.signature);
formData.append("key", auth.directory + "/" + auth.filename);
formData.append("file", {
uri: asset?.uri,
name: asset?.filename,
type: fileType,
});
const uploadResponse = await fetch(auth.host, {
method: "POST",
body: formData,
});
2024-08-05 18:59:30 +08:00
// console.log("uploadResponse", uploadResponse);
2024-07-16 20:20:12 +08:00
if (uploadResponse.status === 200) {
const md5 = uploadResponse.headers.map.etag.substring(
1,
uploadResponse.headers.map.etag.length - 1
);
const videoCover = await generateThumbnail();
const videoCoverId = await uploadImage(videoCover);
const item = {
src_id: auth.directory + "/" + auth.filename,
cover_id: videoCoverId,
md5: md5,
dur: asset?.duration,
fmt: fileType,
};
2024-08-05 18:34:44 +08:00
const base = baseRequest();
const response = await fetch(`/api/media/c_upload`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
mtype: 2,
item: item,
...base,
}),
});
2024-07-16 20:20:12 +08:00
const data = await response.json();
if (data.ret === -1) {
Toast.show({
type: "error",
text1: data.msg,
topOffset: 60,
});
return;
}
return data.data.ret_item.id;
} else {
Toast.show({
type: "error",
text1: "上传视频失败",
topOffset: 60,
});
const failId = await getFailId();
return failId?.video_id_for_upload_fail;
}
} catch (error) {
2024-08-05 18:59:30 +08:00
// console.log("Error occurred while getting or uploading data:", error);
2024-07-16 20:20:12 +08:00
Toast.show({
type: "error",
text1: "上传视频失败",
topOffset: 60,
});
const failId = await getFailId();
return failId?.video_id_for_upload_fail;
}
}
2024-07-02 15:09:48 +08:00
//上传多个图片
export async function multiUploadImage(assets) {
2024-08-05 18:59:30 +08:00
// console.log("assets", assets);
2024-07-02 15:09:48 +08:00
let ids = { image_ids: [], video_ids: [] };
await Promise.all(
2024-07-24 13:53:12 +08:00
assets.map(async (asset) => {
2024-08-05 18:34:44 +08:00
const id = await uploadImage(asset);
2024-08-02 22:12:54 +08:00
// debugger;
2024-07-02 15:09:48 +08:00
ids.image_ids.push(id);
})
);
2024-07-16 20:20:12 +08:00
2024-07-02 15:09:48 +08:00
return ids;
}