uni-app 圖片上傳實戰

uni.uploadFile()
將本地資源上傳到開發者服務器
客戶端發起一個post請求
content-type

multipart/form-data

通過uni.chooseImage獲取一個本地資源的臨時文件路徑後
將本地資源上傳到指定服務器

url String 是 開發者服務器 url 

files Aarry 否 需要上傳的文件列表

filePath String 是 要上傳文件資源的路徑

name String 是 文件對應的key

header Object 否 HTTP 請求 Header, header 中不能設置 Referer 

uploadTask 對象的方法列表

onProgressUpdate callback 監聽上傳進度變化

abort 中斷上傳任務

onProgressUpdate 返回參數說明
實戰頁面

<progress :percent="percent" stroke-width="10"></progress>

<button type="primary" :loading="loading" :disabled="disabled" @click="upload">選擇照片</button>
data:{
  percent:0,
  loading:false,
  disabled:false
 },
upload : function(){
   _self = this;
   uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'], //可以指定是原圖還是壓縮圖,默認二者都有
    sourceType: ['album'], //從相冊選擇
    success: function (res) {
     const tempFilePaths = res.tempFilePaths;
     const uploadTask = uni.uploadFile({
      url : 'https://demo.hcoder.net/index.php?c=uperTest',
      filePath: tempFilePaths[0],
      name: 'file',
      formData: {
       'user': 'test'
      },
      success: function (uploadFileRes) {
       console.log(uploadFileRes.data);
      }
     });
 
     uploadTask.onProgressUpdate(function (res) {
      _self.percent = res.progress;
      console.log('上傳進度' + res.progress);
      console.log('已經上傳的數據長度' + res.totalBytesSent);
      console.log('預期需要上傳的數據總長度' + res.totalBytesExpectedToSend);
     });
    },
    error : function(e){
     console.log(e);
    }
   });
  }
 },

php

<?php
class uperTestController extends witController{
    public function index(){
        if(!empty($_FILES['file'])){
            //獲取擴展名
            $exename  = $this->getExeName($_FILES['file']['name']);
            if($exename != 'png' && $exename != 'jpg' && $exename != 'gif'){
                exit('不允許的擴展名');
            }
            $imageSavePath = uniqid().'.'.$exename;
            if(move_uploaded_file($_FILES['file']['tmp_name'], $imageSavePath)){
                echo $imageSavePath;
            }
        }
    }
    
    public function getExeName($fileName){
        $pathinfo      = pathinfo($fileName);
        return strtolower($pathinfo['extension']);
    }
}

uni.chooseImage(OBJECT) 從本地相冊選擇圖片或使用相機拍照
文件的臨時路徑,在應用本次啓動期間可以正常使用,如需持久保存,需在主動調用 uni.saveFile,在應用下次啓動時才能訪問得到。

tempFilePaths 
StringArray 圖片的本地文件路徑列表

tempFiles 
ObjectArray 圖片的本地文件列表,每一項是一個 File 對象

File 對象結構如下

path String 本地文件路徑
size Number 本地文件大小,單位:B
uni.chooseImage({
 count: 6, // 默認9
 sizeType: ['original', 'compressed'], // 原圖,壓縮圖
 sourceType: ['album'], // 從相冊選擇
 success: function(res) {
  console.log(JSON.stringify(res.tempFilePaths));
    }
});
uni.previewImage();

預覽圖片

current 當前顯示圖片的鏈接

urls 需要預覽的圖片鏈接列表
uni.chooseImage({
 count: 6,
 sizeType: ['original','compressed'],
 sourceType: ['album'],
 success: function(res) {
  // 預覽圖片
    uni.previewImage({
     urls: res.tempFilePaths
    });
 }

uni.getImageInfo()
獲取圖片信息

orientation 參數說明

枚舉值 說明

up 默認
down 180度旋轉
left 逆時針旋轉90度
right 順時針旋轉90度

up-mirrored 同up,但水平翻轉
down-mirrored 同down,但水平翻轉
left-mirrored 同left,但垂直翻轉
right-mirrored 同right,但垂直翻轉
uni.chooseImage({
    count: 1,
    sourceType: ['album'],
    success: function (res) {
        uni.getImageInfo({
            src: res.tempFilePaths[0],
            success: function (image) {
                console.log(image.width);
                console.log(image.height);
            }
        });
    }
});

uni.saveImageToPhotosAlbum(OBJECT)

保存圖片到系統相冊

filePath 圖片文件路徑

uni.chooseImage({
    count: 1,
    sourceType: ['camera'],
    success: function (res) {
        uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePaths[0],
            success: function () {
                console.log('save success');
            }
        });
    }
});

若本號內容有做得不到位的地方(比如:涉及版權或其他問題),請及時聯繫我們進行整改即可,會在第一時間進行處理。


請點贊!因爲你們的贊同/鼓勵是我寫作的最大動力!

歡迎關注達達的簡書!

這是一個有質量,有態度的博客

博客

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章