90 lines
2.6 KiB
JavaScript
90 lines
2.6 KiB
JavaScript
/**
|
||
* 上传小程序「资质公示」静态图到 OSS:static/mini-user/qualification-disclosure.png
|
||
* 用法(在 server/dukang-api):
|
||
* node scripts/upload-qualification-disclosure.mjs [本地 png 路径]
|
||
* 也可设环境变量 QUALIFICATION_DISCLOSURE_LOCAL。
|
||
*/
|
||
import { readFileSync, existsSync } from 'fs';
|
||
import { resolve, dirname, isAbsolute } from 'path';
|
||
import { fileURLToPath } from 'url';
|
||
import { createRequire } from 'module';
|
||
|
||
const require = createRequire(import.meta.url);
|
||
const OSS = require('ali-oss');
|
||
|
||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||
const apiRoot = resolve(__dirname, '..');
|
||
|
||
function loadEnvFile(path) {
|
||
if (!existsSync(path)) return {};
|
||
const out = {};
|
||
for (const line of readFileSync(path, 'utf8').split(/\r?\n/)) {
|
||
const m = line.match(/^([A-Z0-9_]+)=(.*)$/);
|
||
if (!m) continue;
|
||
let v = m[2];
|
||
if (
|
||
(v.startsWith('"') && v.endsWith('"')) ||
|
||
(v.startsWith("'") && v.endsWith("'"))
|
||
) {
|
||
v = v.slice(1, -1);
|
||
}
|
||
out[m[1]] = v;
|
||
}
|
||
return out;
|
||
}
|
||
|
||
const env = {
|
||
...loadEnvFile(resolve(apiRoot, '.env.production')),
|
||
...loadEnvFile(resolve(apiRoot, '.env.development')),
|
||
...loadEnvFile(resolve(apiRoot, '.env')),
|
||
};
|
||
|
||
const accessKeyId = env.OSS_ACCESS_KEY_ID || '';
|
||
const accessKeySecret = env.OSS_ACCESS_KEY_SECRET || '';
|
||
const bucket = env.OSS_BUCKET || '';
|
||
const region = env.OSS_REGION || 'oss-cn-beijing';
|
||
const cdnBase = (env.OSS_CDN_BASE || '').replace(/\/$/, '');
|
||
|
||
if (!accessKeyId || !accessKeySecret || !bucket) {
|
||
console.error('缺少 OSS_ACCESS_KEY_ID / OSS_ACCESS_KEY_SECRET / OSS_BUCKET');
|
||
process.exit(1);
|
||
}
|
||
|
||
const argPath = process.argv[2]?.trim() || env.QUALIFICATION_DISCLOSURE_LOCAL?.trim() || '';
|
||
if (!argPath) {
|
||
console.error(
|
||
'请传入本地 png 路径,例如:\n node scripts/upload-qualification-disclosure.mjs D:/tmp/qualification-disclosure.png',
|
||
);
|
||
process.exit(1);
|
||
}
|
||
|
||
const localFile = isAbsolute(argPath) ? argPath : resolve(process.cwd(), argPath);
|
||
if (!existsSync(localFile)) {
|
||
console.error('本地文件不存在:', localFile);
|
||
process.exit(1);
|
||
}
|
||
|
||
const ossKey = 'static/mini-user/qualification-disclosure.png';
|
||
const client = new OSS({
|
||
region,
|
||
accessKeyId,
|
||
accessKeySecret,
|
||
bucket,
|
||
});
|
||
|
||
const buffer = readFileSync(localFile);
|
||
await client.put(ossKey, buffer, {
|
||
mime: 'image/png',
|
||
headers: {
|
||
'Content-Disposition': 'inline',
|
||
'Cache-Control': 'public, max-age=31536000',
|
||
},
|
||
});
|
||
|
||
const url = cdnBase
|
||
? `${cdnBase}/${ossKey}`
|
||
: `https://${bucket}.${region}.aliyuncs.com/${ossKey}`;
|
||
|
||
console.log('uploaded:', ossKey);
|
||
console.log('url:', url);
|