一、使用uni.uploadFile上傳文件
1、首先在頁面中添加文件選擇器(input type=”file” accept=”image/*”)的組件。
2、為文件選擇器添加change事件,處理用戶選擇的文件並調用uni.uploadFile()函數上傳文件。
3、完成文件上傳後,服務器返回的數據可以在uni.uploadFile()的回調函數中處理。
<template>
<view>
<input type="file" accept="image/*" @change="uploadFile" />
</view>
</template>
<script>
export default {
methods: {
uploadFile(event) {
const file = event.target.files[0];
uni.uploadFile({
url: 'http://localhost:3000/upload',
filePath: file.tempFilePath,
name: 'file',
success(res) {
console.log(res.data);
}
});
}
}
}
</script>
二、設置請求頭和參數
1、通過uni.uploadFile()第三個參數的header屬性設置請求頭。
2、通過uni.uploadFile()第三個參數的formData屬性設置參數。
<script>
export default {
methods: {
uploadFile(event) {
const file = event.target.files[0];
uni.uploadFile({
url: 'http://localhost:3000/upload',
filePath: file.tempFilePath,
name: 'file',
header: {
'Authorization': 'Bearer ' + uni.getStorageSync('token')
},
formData: {
'name': 'avatar'
},
success(res) {
console.log(res.data);
}
});
}
}
}
</script>
三、限制文件類型和大小
1、通過accept參數限制文件類型。
2、通過fileSize參數限制文件大小。
<template>
<view>
<input type="file" accept="image/png,image/jpeg" :fileSize="1024 * 1024" @change="uploadFile" />
</view>
</template>
<script>
export default {
methods: {
uploadFile(event) {
const file = event.target.files[0];
uni.uploadFile({
url: 'http://localhost:3000/upload',
filePath: file.tempFilePath,
name: 'file',
header: {
'Authorization': 'Bearer ' + uni.getStorageSync('token')
},
formData: {
'name': 'avatar'
},
success(res) {
console.log(res.data);
}
});
}
}
}
</script>
四、顯示上傳進度
1、通過uni.uploadFile()函數的progress屬性實現上傳進度顯示。
2、在頁面中添加進度條組件,並將進度值綁定到data中的progress變量。
<template>
<view>
<input type="file" accept="image/png,image/jpeg" :fileSize="1024 * 1024" @change="uploadFile" />
<progress :percent="progress" />
</view>
</template>
<script>
export default {
data() {
return {
progress: 0
}
},
methods: {
uploadFile(event) {
const file = event.target.files[0];
uni.uploadFile({
url: 'http://localhost:3000/upload',
filePath: file.tempFilePath,
name: 'file',
header: {
'Authorization': 'Bearer ' + uni.getStorageSync('token')
},
formData: {
'name': 'avatar'
},
success(res) {
console.log(res.data);
},
progressCallback(res) {
this.progress = res.progress;
}
});
}
}
}
</script>
五、使用uni.compressImage()壓縮圖片
1、上傳大量圖片可能會導致上傳速度變慢,同時也會消耗用戶手機的流量。
2、通過uni.compressImage()函數將圖片壓縮後再上傳,可以減少上傳時間和流量消耗。
<script>
export default {
methods: {
uploadFile(event) {
const file = event.target.files[0];
uni.compressImage({
src: file.tempFilePath,
quality: 80,
success(res) {
uni.uploadFile({
url: 'http://localhost:3000/upload',
filePath: res.tempFilePath,
name: 'file',
header: {
'Authorization': 'Bearer ' + uni.getStorageSync('token')
},
formData: {
'name': 'avatar'
},
success(res) {
console.log(res.data);
},
progressCallback(res) {
console.log(res.progress);
}
});
}
});
}
}
}
</script>
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/183450.html