2025-05-12 04:30:17 +08:00

77 lines
2.1 KiB
TypeScript

import { getBufferHash, getHash } from '@/uitls/hash.ts';
import FormData from 'form-data';
export const handleResponse = async (err: any, res: any) => {
return new Promise((resolve) => {
if (err) {
console.error('Upload failed:', err);
resolve({ code: 500, message: err });
return;
}
// 处理服务器响应
let body = '';
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
try {
const res = JSON.parse(body);
resolve(res);
} catch (e) {
resolve({ code: 500, message: body });
}
});
});
};
export const getFormParams = (opts: UploadOptions, headers: any): FormData.SubmitOptions => {
const url = new URL(opts.url);
if (opts.token) {
// url.searchParams.append('token', opts.token);
}
const value: FormData.SubmitOptions = {
path: url.pathname + url.search,
host: url.hostname,
method: 'POST',
protocol: url.protocol === 'https:' ? 'https:' : 'http:',
port: url.port || (url.protocol === 'https:' ? 443 : 80),
headers: {
Authorization: 'Bearer ' + opts.token,
...headers,
},
};
console.log('getFormParams', value);
return value;
};
type UploadOptions = {
url: string | URL;
file?: string | Buffer | File;
token?: string;
form?: FormData;
needHash?: boolean;
};
export const upload = (opts: UploadOptions): Promise<{ code?: number; message?: string; [key: string]: any }> => {
const form = opts?.form || new FormData();
if (!opts.form) {
let hash = '';
let value: any;
let type = 'string';
if (typeof opts.file === 'string') {
value = Buffer.from(opts.file);
} else {
type = 'buffer';
value = opts.file;
}
form.append('file', value);
if (opts.needHash) {
hash = getBufferHash(value);
opts.url = new URL(opts.url.toString());
opts.url.searchParams.append('hash', hash);
}
}
const headers = form.getHeaders();
return new Promise((resolve) => {
form.submit(getFormParams(opts, headers), (err, res) => {
handleResponse(err, res).then(resolve);
});
});
};