uni.uploadFile(OBJECT)
將本地資源上傳到開發者服務器,客戶端發起一個POST請求,其中content-type為multipart/form-data.
如頁面通過uni.chooseImage等接口獲得一個本地資源的臨時危機路徑后,可通過此接口將本地資源上傳到指定服務器。
OBJECT 參數說明:
| 參數名 | 類型 | 必填 | 說明 | 平台支持 |
| url | String | 是 | 開發者服務器url | |
| files | Aarry | 否 | 需要上傳的文件列表。使用files時,filePath和name不生效。 | 5+app |
| filePath | String | 是 | 要上傳文件資源的路徑 | |
| name | String | 是 | 文件對應得key,開發者在服務器端通過這個key可以獲取到文件二進制內容。 | |
| header | Object | 否 | HTTP請求 Header,header中不能設置Referer。 | |
| formData | Object | 否 | HTTP請求中其他額外的form data | |
| success | Function | 否 | 接口調用成功的回調函數 | |
| fail | Function | 否 | 接口調用失敗的回調函數 | |
| complete | Function | 否 | 接口回調結束的回調函數(調用成功、失敗都會執行) |
圖片上傳及進度條顯示
<template>
<View>
{{name}}---{{age}}
<!-- 上傳進度條 -->
<progress :percent="percent" stroke-width="10"></progress>
<button @click="img">選擇照片</button>
</View>
</template>
<script>
var _self;
export default {
data(){
return{
percent:0,
age:'',
name:''
}
},
onLoad: function (option) { //option為object類型,會序列化上個頁面傳遞的參數
console.log(option.age); //打印出上個頁面傳遞的參數。
console.log(option.name); //打印出上個頁面傳遞的參數。
this.age=option.age;
this.name=option.name;
_self=this;
},
methods:{
img:function(){
uni.chooseImage({
count: 1,
sizeType:"compressed",
success: (res) => {
console.log(res);
// 瀏覽
// uni.previewImage({
// urls: res.tempFilePaths
// })
var imgsFile=res.tempFilePaths[0];
var uper=uni.uploadFile({
url: 'https://demo.hcoder.net/index.php?c=uperTest',
filePath: imgsFile,
name: 'file',
success:function(res1){
console.log(res1);
}
});
//修改進度條
uper.onProgressUpdate(function(e){
_self.percent=e.progress;
console.log('上傳進度'+e.progress);
console.log('已上傳數據長度'+e.totalBytesSent);
console.log('數據總長度'+e.totalBytesExpectedToSend);
});
}
})
}
}
}
</script>
<style>
</style>
uni.downloadFile(OBJECT)
下載文件資源到本地,客戶端直接發起一個HTTP GET請求,返回文件的本地臨時路徑。
OBJECT 參數說明:
| 參數名 | 類型 | 必填 | 說明 |
| url | String | 是 | 下載資源的url |
| header | Object | 否 | HTTP請求Header,header中不能設置Referer |
| success | Function | 否 | 下載成功后以tempFilePath的形式給頁面,res={tempFilePath:'文件的臨時路徑'} |
| fail | Function | 否 | 接口調用失敗的回調函數 |
| complete | Function | 否 | 接口調用結束的回調函數(調用成功、失敗都會執行) |
const downloadTask=uni.downloadFile({ url: 'http://www.example.com/file/test',//下載地址 success:function(res){ if(res.statusCode===200){ console.log('下載成功'); } } }); // 下載監聽 downloadTask.onProgressUpdate(function(res){ console.log('下載進度'+res.progress); console.log('已經下載數據長度'+res.totalBytesWritten); console.log('數據總長度'+res.totalBytesExpectedToWrite); })
