uniapp的h5兼容上傳人臉

其實就是h5上傳人臉,但是有些點還是要注意的
1.注意點一:uniapp是不支持原生input的,所以我們只能模擬

// 隱式創建一個input控件,然後實現直接訪問相冊
                let inputUploadObj = '';
                inputUploadObj = document.createElement('input')
                inputUploadObj.setAttribute('id', 'input_upload_ID');
                inputUploadObj.setAttribute('type', 'file');
                // 添加這個屬性,就可以喚起相機的功能
                inputUploadObj.setAttribute('capture', 'camera');
                // 這裏如果不加屬性 accept 是 "image/*" 或者 "video/*",就默認打開攝像頭,既可以拍照也可以錄像
                inputUploadObj.setAttribute('accept', 'image/*');
                inputUploadObj.setAttribute("style", 'visibility:hidden');
                // 這裏將創建的隱式input控件拼接到body的最後面,會增加頁面的長度,所以要在適當的時候,移除掉這個隱式創建的input控件
                document.body.appendChild(inputUploadObj);
                // 這裏是模擬點擊了input控件
                inputUploadObj.click();
                inputUploadObj.onchange=async (event)=>{
                    let file = event.target.files[0];
                    const currentFile = await util.compressImg(file);//這裏是圖片壓縮
                    let url="";
                    if (window.createObjectURL != undefined) { // basic
                            url = window.createObjectURL(currentFile);
                        } else if (window.URL != undefined) { // mozilla(firefox)
                            url = window.URL.createObjectURL(currentFile);
                        } else if (window.webkitURL != undefined) { // webkit or chrome
                            url = window.webkitURL.createObjectURL(currentFile);
                        }
                        util.setStorageSync('uploadPhotoPath', url);
                        this.uploadPath(url);
                }

2.注意點二:壓縮圖片,因爲小程序的壓縮我們用不了,所以只能用其他插件壓縮,這裏我們使用image-conversion就行壓縮,壓縮效果很好,還能指定壓縮大小
首先就是安裝

import { compressAccurately } from 'image-conversion';
export function compressImg(file) {
  return new Promise(resolve => {
    compressAccurately(file, 170).then(res => {
      // The res in the promise is a compressed Blob type (which can be treated as a File type) file;
      const currentFile = new File([res], file.name, { type: file.type });
      resolve(currentFile);
    });
  });
}

下面的就比較好說,大家應該都會了,不會的在call我吧

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