bun 多文件上传会有问题
This commit is contained in:
63
src/module/download/upload.ts
Normal file
63
src/module/download/upload.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
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,
|
||||
},
|
||||
};
|
||||
return value;
|
||||
};
|
||||
type UploadOptions = {
|
||||
url: string | URL;
|
||||
file?: string | Buffer | File;
|
||||
token?: string;
|
||||
form?: FormData;
|
||||
};
|
||||
export const upload = (opts: UploadOptions): Promise<{ code?: number; message?: string; [key: string]: any }> => {
|
||||
const form = opts?.form || new FormData();
|
||||
if (!opts.form) {
|
||||
if (typeof opts.file === 'string') {
|
||||
form.append('file', Buffer.from(opts.file));
|
||||
} else {
|
||||
form.append('file', opts.file);
|
||||
}
|
||||
}
|
||||
const headers = form.getHeaders();
|
||||
return new Promise((resolve) => {
|
||||
form.submit(getFormParams(opts, headers), (err, res) => {
|
||||
handleResponse(err, res).then(resolve);
|
||||
});
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user