ossUpload.js
6.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import api from "~/api/api.js";
import base64 from "./base64.js";
import Crypto from "./crypto.js";
const baseConfig = {
// 阿里云oss域名 格式:https://xxx.oss-cn-xxx.aliyuncs.com
OSS_DOMAIN: "https://glsk-oss.oss-cn-shenzhen.aliyuncs.com",
// 文件直传到阿里云oss时需用到
ACCESSKEYID: "LTAI5tCRcCUgd7bt1J7JY596",
ACCESSKEYSECRET: "kJos9mgylkR5ztosnDt8Asrc3ulgqy",
BUKET_NAME: "glsk-oss",
FOLDER: "usedCar/",
// 与后端约定的token字段名
TOKEN_NAME: "glsk-oss",
// PROTOCAL: 'http',
// SERVER: 'app-admin-server.test.glsx.com.cn',
// SOCKET_PORT: '9081',
// HTTP_PORT: '3000',
HTTP_SERVER: "http://app-admin-server.glsx.com.cn",
SOCKET_SERVER: "http://app-admin-server.glsx.com.cn",
FILE_UPLOAD_URL: "file/upload",
};
const config = {
bucketName: baseConfig.BUKET_NAME,
folder: baseConfig.FOLDER,
uploadUrl: baseConfig.OSS_DOMAIN + "/", // 默认存在根目录后面要跟个'/' (在你当前小程序的后台的uploadFile 合法域名也要配上这个域名)
AccessKeySecret: baseConfig.ACCESSKEYSECRET, // AccessKeySecret 去你的阿里云上控制台上找
OSSAccessKeyId: baseConfig.ACCESSKEYID, // AccessKeyId 去你的阿里云上控制台上找
timeout: 87600, // 这个是上传文件时Policy的失效时间
};
/**
* 上传文件到阿里云oss
* @param {Object} file 文件信息,支持格式:{ fileType, size, tempFilePath, thumb, type, url }
* - tempFilePath / url: 本地临时路径,用于上传
* - size: 文件大小(字节)
* - fileType / type: 文件类型,如 "image"
* @return 完整的图片/文件地址
*/
const uploadFile = async function (file) {
const res = await api.getSceneMarketConfig();
console.log(res, "res");
// const { data } = await api.fetchApiConfig(config.bucketName);
// console.log(data, "data");
// return;
// 兼容只传 file 对象:从 tempFilePath 或 url 取上传路径
const filePath = file.tempFilePath || file.url;
if (!filePath) {
return Promise.reject(
new Error("缺少文件路径:请提供 tempFilePath 或 url")
);
}
console.log("上传文件到阿里云oss", file);
return new Promise(async (resolve, reject) => {
// 从路径中提取文件后缀(支持 http://tmp/xxx.jpg 或 本地路径)
const getExtension = (path) => {
if (!path) return "";
const name = path.split("/").pop() || path;
const lastDot = name.lastIndexOf(".");
return lastDot > -1 ? name.slice(lastDot + 1).toLowerCase() : "";
};
const fileExtension = getExtension(filePath);
// 添加文件大小限制检查
if (file.size) {
const imageTypes = ["jpg", "jpeg", "png", "gif", "bmp"];
const videoTypes = ["mp4", "avi", "mov", "wmv", "flv", "mkv"];
const fileSizeMB = file.size / (1024 * 1024);
if (imageTypes.includes(fileExtension) && fileSizeMB > 10) {
// uni.showToast({ title: "图片上传最大10MB", icon: "none" });
reject(new Error("图片上传最大10MB"));
return;
}
if (videoTypes.includes(fileExtension) && fileSizeMB > 100) {
// uni.showToast({ title: "视频上传最大100MB", icon: "none" });
reject(new Error("视频上传最大100MB"));
return;
}
}
const timestamp = Date.now();
const randomStr = Math.random().toString(36).substring(2, 10);
const randomNum = timestamp + "_" + randomStr;
const ext = fileExtension || "jpg"; // 无后缀时默认 jpg(常见于选图)
let aliyunFileKey = config.folder + randomNum + "." + ext;
console.log(aliyunFileKey, "aliyunFileKey");
const aliyunServerURL = config.uploadUrl;
// 4. 生成 policy,并根据 policy 计算签名
const { lsaccessKeySecret, securityToken, lsaccessKeyId } =
await getOssToken();
const { policy, signature } = getPolicyBase64(
aliyunFileKey,
lsaccessKeySecret
);
console.log(signature, "signaturesignaturesignature");
// 5. 组装 x-oss-credential,AccessKeyId 使用 STS 返回的临时 key(lsaccessKeyId)
const accessKeyId = lsaccessKeyId || config.OSSAccessKeyId;
const formData = {
key: aliyunFileKey,
OSSAccessKeyId: accessKeyId,
policy: policy,
signature: signature,
success_action_status: "200",
"x-oss-security-token": securityToken,
};
console.log(formData, "formData");
wx.uploadFile({
url: aliyunServerURL,
filePath: filePath,
name: "file",
formData: formData,
success: function (res) {
console.log(res, 444);
if (res.statusCode != 200) {
reject();
} else {
// 上传成功后删除临时文件(uni.removeSavedFile 需传 filePath)
wx.getFileSystemManager().removeSavedFile({
filePath: filePath,
success: function (res) {
console.log(res);
},
});
}
const rawUrl = aliyunServerURL + aliyunFileKey;
resolve(rawUrl);
},
fail: function (err) {
console.log(err, 555);
err.domainName = aliyunServerURL;
reject(err);
},
});
});
};
const getPolicyBase64 = function (aliyunFileKey, accessKeySecret) {
// 生成过期时间(1小时后)
const expiration = new Date(Date.now() + 3600 * 1000).toISOString();
// 构造 policy(定义上传规则)
const policyObj = {
expiration: expiration,
conditions: [
{ bucket: config.bucket },
["eq", "$key", aliyunFileKey],
["content-length-range", 0, 1048576000], // 最大 1GB
],
};
// Base64 编码 policy
const policyBase64 = base64.encode(JSON.stringify(policyObj));
console.log(accessKeySecret, "policyBase64");
// HMAC-SHA1 签名(使用 AccessKeySecret)
const bytes = Crypto.HmacSHA1(policyBase64, accessKeySecret);
const signature = Crypto.enc.Base64.stringify(bytes);
return {
policy: policyBase64,
signature: signature,
};
};
const getOssToken = async function () {
console.log("getOssToken");
const res = await api.getToken({});
// 根据通用 request 封装,这里的 res 就是 response.data,
// 真实业务数据在 res.data 里
const tokenData = res && res.data ? res.data : res || {};
const { lsaccessKeySecret, securityToken, lsaccessKeyId } = tokenData;
if (!lsaccessKeySecret) {
console.error("获取 OSS Token 失败,lsaccessKeySecret 为空:", res);
throw new Error("获取 OSS Token 失败");
}
return {
lsaccessKeySecret,
securityToken,
lsaccessKeyId,
};
};
/**
* 用于图片展示/回显时拼接 OSS 图片处理参数(视频不处理)
* @param {string} url 原始 URL
* @param {boolean} [isVideo] 是否为视频
* @returns {string} 展示用 URL
*/
function getImageDisplayUrl(url, isVideo) {
if (!url) return url;
if (isVideo) return url;
if (url.indexOf("x-oss-process=") >= 0) return url;
const sep = url.indexOf("?") >= 0 ? "&" : "?";
return url + sep + "x-oss-process=image/format,jpg/quality,q_100";
}
module.exports = { uploadFile, getImageDisplayUrl };