微信小程序中使用put请求来实现文件上传,在基于uniapp框架下,官方提供的文件上传组件默认只支持post请求,经过两天“学习”(上网找资料),最后在组里后端的指导下成功实现put上传文件至某三方服务器! 话不多说,直接上代码:
组件用的uv-ui,www.uvui.cn/components/… ,具体属性配置可看官网。
import Upload from "@/uni_modules/uv-upload/components/uv-upload/uv-upload.vue";
<Upload
:fileList="vedioList2"
:maxCount="1"
@afterRead="afterRead"
@delete="deleteVedio"
:previewFullVideo="false"
:previewFullImage="false"
accept="video">
</Upload>
上传函数处理,利用getFileSystemManager和ArrayBuffer进行文件处理
const afterRead = async ({ file }) => {
console.log(file);
uni.showLoading({
title: "上传中",
mask: true,
});
const urlRes = await getUploadUrl(file.url);//从后端获取上传目标服务器地址
const fs = uni.getFileSystemManager();
const ab = new ArrayBuffer(file.size);
fs.open({
filePath: file.url,
flag: "r",
success(res) {
fs.read({
fd: res.fd,
arrayBuffer: ab,
length: file.size,
success(res) {
uni.request({
method: "PUT",
url: urlRes.data.url.replace("http:", "https:"),
data: res.arrayBuffer,
header: {
"Content-Type": "multipart/form-data",
},
success: () => {
uni.hideLoading();
uni.showToast({
title: "上传成功",
icon: "success",
});
},
fail: (error) => {
uni.hideLoading();
uni.showToast({
title: "上传失败",
icon: "none",
});
console.error("上传失败:", error);
},
});
},
fail(error) {
console.log(error);
},
});
},
});
};