上传单个文件
html
<script setup>
const handleUploadClick = () => {
console.log("上传文件")
uni.chooseImage({
success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths;
console.log("用户选择的图片:", tempFilePaths)
uni.uploadFile({
url: 'http://192.168.234.138:8889/upload',
filePath: tempFilePaths[0],
name: 'file',
success: (uploadFileRes) => {
console.log("上传文件成功", uploadFileRes.data);
}
});
}
});
}
</script>
<template>
<view>
<view @click="handleUploadClick" class="button">
上传文件
</view>
</view>
</template>
<style scoped>
.button {
display: inline-block;
background-color: aqua;
padding: 10rpx 20rpx;
border-radius: 5%;
}
</style>
上传多个文件
上传多个文件的功能有个细节需要注意,那就是files不能直接使用读取到的文件列表,官方文档给出如下解释。
按照官方文档的要求,最终成功的代码如下:
html
<script setup>
const handleUploadClick = () => {
console.log("上传文件")
uni.chooseImage({
success: (chooseImageRes) => {
const tempFilePaths = chooseImageRes.tempFilePaths;
console.log("用户选择的图片:", tempFilePaths)
let files = []
for (let filePath of tempFilePaths){
console.log("filePath", filePath)
files.push({
name: "file",
uri: filePath,
})
}
uni.uploadFile({
url: 'http://192.168.234.138:8889/uploads',
files: files,
success: (uploadFileRes) => {
console.log("上传文件成功", uploadFileRes.data);
}
});
}
});
}
</script>
<template>
<view>
<view @click="handleUploadClick" class="button">
上传文件
</view>
</view>
</template>
<style scoped>
.button {
display: inline-block;
background-color: aqua;
padding: 10rpx 20rpx;
border-radius: 5%;
}
</style>