feat: 完善小程序和native的upload对put方法的处理

This commit is contained in:
Pan Qiancheng 2025-10-16 09:15:41 +08:00
parent f924d06fa3
commit 3b6091db78
2 changed files with 80 additions and 21 deletions

View File

@ -7,15 +7,56 @@ export class Upload {
uploadUrl: string,
formData: Record<string, any>,
autoInform?: boolean,
getPercent?: Function,
method: "POST" | "PUT" | "PATCH" = "POST"
): Promise<any> {
const wxUploadFile = promisify(wx.uploadFile);
const result = await wxUploadFile({
url: uploadUrl,
filePath: file as string,
name: name || 'file',
formData: formData,
});
const isPut = method === "PUT";
return result;
if (isPut) {
return new Promise((resolve, reject) => {
const fs = wx.getFileSystemManager();
fs.readFile({
filePath: file as string,
success: (fileRes) => {
// 使用 PUT 方法上传
wx.request({
url: uploadUrl,
method: 'PUT',
data: fileRes.data, // ArrayBuffer 格式
header: {
'Content-Type': 'image/jpeg', // 根据实际文件类型设置
},
success: (uploadRes) => {
if (uploadRes.statusCode === 200) {
resolve(uploadRes);
} else {
reject(new Error(`HTTP Error: ${uploadRes.statusCode}`));
}
},
fail: (err) => {
console.error('上传失败', err);
reject(err);
}
});
},
fail: (err) => {
console.error('读取文件失败', err);
reject(err);
}
});
});
} else {
const wxUploadFile = promisify(wx.uploadFile);
const result = await wxUploadFile({
url: uploadUrl,
filePath: file as string,
name: name || 'file',
formData: formData,
});
return result;
}
}
}

View File

@ -6,20 +6,38 @@ export class Upload {
name: string,
uploadUrl: string,
formData: Record<string, any>,
autoInform?: boolean
autoInform?: boolean,
getPercent?: Function,
method: "POST" | "PUT" | "PATCH" = "POST"
): Promise<any> {
const formData2 = new FormData();
for (const key of Object.keys(formData)) {
formData2.append(key, formData[key]);
const isPut = method === "PUT";
if (isPut) {
// S3 预签名上传
const headers: Record<string, string> = {};
if (file instanceof File) {
headers["Content-Type"] = file.type || "application/octet-stream";
}
const result = await fetch(uploadUrl, {
method: "PUT",
headers,
body: file as any,
});
return result;
} else {
// 表单上传
const formData2 = new FormData();
for (const key of Object.keys(formData)) {
formData2.append(key, formData[key]);
}
formData2.append(name || "file", file as File);
const result = await fetch(uploadUrl, {
method,
body: formData2,
});
return result;
}
formData2.append(name || 'file', file as File);
const options = {
body: formData2,
method: 'POST',
};
const result = await fetch(uploadUrl, options);
return result;
}
}