小程序總結(jié)(二十一)- 基于Taro + typescript的選擇上傳照片

可選擇多張圖片進(jìn)行上傳(接口是一張一張的上傳的)


<View className="textarea-title">上傳照片</View>
                        <View className="patient-document-pic-box">
                            {files.map((file, index) => 
                                <View className="temp-file-pic-box" key={'file' + index}>
                                    <Image className="temp-file-pic" src={file.path}></Image>
                                    <Image className="close-icon" src='https://kano.guahao.cn/Efm199642756' onClick={this.onDeletePhoto.bind(this, index)}></Image>
                                    {this.state.showLoadingLayer && !file.isUploaded &&
                                    <View className="pic-layer">
                                        <View className="layer-loading">
                                            <View className="layer-progress"></View>
                                            {this.state.showUploadingText && <Text className="layer-text">正在上傳</Text>}
                                        </View>
                                    </View>}
                                </View>
                            )}
                            {
                                this.state.files.length < 9 &&
                                <View className="camera-pic-box" onClick={this.onChooseImg.bind(this)}>
                                    <Image className="camera-pic" src='https://kano.guahao.cn/GEm199642253'></Image>
                                    <Text className="add-text">添加照片</Text>
                                </View>
                            }
                        </View>

.patient-document-pic-box, .temp-file-box {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        .temp-file-pic-box {
            position: relative;
            .temp-file-pic {
                width: 150px;
                height: 150px;
                margin-right: 20px;
                margin-bottom: 20px;
                flex-shrink: 0;
            }
            .close-icon {
                width: 40px;
                height: 40px;
                position: absolute;
                top: -20px;
                right: 0px;
                z-index: 2;
            }
            .pic-layer {
                width: 150px;
                height: 150px;
                background: rgba(0,0,0,.6);
                position: absolute;
                top: 0;
                display: flex;
                justify-content: center;
                align-items: center;
                .layer-text {
                    font-size: 18px;
                    color: #fff;
                    opacity: 0.8;
                    position: absolute;
                    left: 50%;
                    transform: translateX(-50%);
                }
                .layer-loading {
                    width: 60px;
                    height: 60px;
                    position: relative;
                    .layer-progress {
                        width: 60px;
                        height: 60px;
                        border-radius: 50%;
                        border: 5px solid #8F8E8C;
                        border-top: 5px solid #fff;
                        position: absolute;
                        left: -5rpx;
                        top: -3rpx;
                        -webkit-animation: spin 2s linear infinite;
                        animation: spin 2s linear infinite;
                    }
                    .layer-text {
                        position: absolute;
                        z-index: 2;
                        top: 50%;
                        transform: translate(-50%,-50%);
                        left: 50%;
                        word-break: keep-all;
                    }
                }
            }
        }
        .camera-pic-box {
            position: relative;
            top: -14px;
            width: 149px;
            height: 149px;
            border: 1Px solid #ddd;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            .camera-pic {
                width: 45px;
                height: 37px;
            }
            .add-text {
                font-size: 18px;
                color: #9B9B9B;
            }
        }
    }

// 關(guān)于typescript的類型定義你可以去掉
onChooseImg (): void {
        const filesLength = this.state.files.length
        this.setState({
            fileIndex: 0
        })
        if (this.state.files.length < 9) {
            Taro.chooseImage({
                sourceType: ['album', 'camera'],
                sizeType: ['compressed'],
                count: 9 - filesLength
            }).then((res:any) => {
                this.setState({
                    files: this.state.files.concat(res.tempFiles).slice(0,9)
                })
                this.setState({
                    showLoadingLayer: true,
                    showUploadingText: true,
                    showWaitingUploadText: true
                })
                // 選中圖片之后就要上傳
                /*這里我一開始直接遍歷res.tempFiles數(shù)組摇予,后來發(fā)現(xiàn)沽讹,我上傳的跟我選中的圖片無法對(duì)上捎迫,所以這里不能直接循環(huán)遍歷選中的圖片數(shù)組*/
                this.onUpload(res.tempFiles, res.tempFiles[this.state.fileIndex])
            }).catch(e=> {console.log(e)})
        } else {
            Taro.showToast({
                title: '最多只能上傳9張圖片统刮!',
                icon: 'none'
            })
        }
    }
     // 這里只在本地刪除
    onDeletePhoto (index:number): void {
        this.state.files.splice(index, 1)
        this.setState({
            files: this.state.files
        })
        for (let i = 0; i < this.state.recordFiles.length; i++) {
            if (index === i) {
                this.state.recordFiles.splice(index, 1)
                this.setState({
                    recordFiles: this.state.recordFiles
                })
                break;
            }
        }
    }
    onUpload (tempArr: Array<IFile>, file: IFile): void {
        const fileObj = file
    
        file && Taro.uploadFile({
            url: `這里換成你的上傳圖片的接口地址`,
            filePath: file.path,
            name: 'file',
            // 根據(jù)情況看是否需要傳token
            header: {
                "Content-Type": "multipart/form-data",
                Authorization: 'Bearer ' + Taro.getStorageSync('UserInfo').accessToken
            },
            // complete比success先執(zhí)行
            complete: () => {
                if (this.state.fileIndex === tempArr.length) {
                    this.setState((preState: any) => {
                        preState.showLoadingLayer = false
                        preState.showUploadingText = false
                        preState.showWaitingUploadText = false
                    })
                } else {
                    let { fileIndex } = this.state
                    fileIndex = fileIndex + 1 // 避免index = 0上傳兩次
                    this.onUpload(tempArr, tempArr[fileIndex])
                }
            },
            success: (res) => {
                let file = JSON.parse(res.data).obj
                // 控制蒙層的顯示
                for (let i = 0; i < this.state.files.length; i++) {
                    if (this.state.files[i].path === fileObj.path) {
                        this.state.files[i].isUploaded = true
                        break;
                    }
                }
                this.setState((preState:any) => {
                    preState.recordFiles = preState.recordFiles.concat(file[0].url)
                    preState.fileIndex = preState.fileIndex + 1
                }, () => {
                    console.log('success fileIndex = ', this.state.fileIndex)
                })
            }
        })
    }

需要在state中定義的數(shù)據(jù):

state = {
  files: [],
  recordFiles: [],
  showLoadingLayer: false,
  showUploadingText: false,
  fileIndex: 0 // 當(dāng)前上傳的圖片索引
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市污抬,隨后出現(xiàn)的幾起案子戈咳,更是在濱河造成了極大的恐慌,老刑警劉巖壕吹,帶你破解...
    沈念sama閱讀 211,639評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件著蛙,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡耳贬,警方通過查閱死者的電腦和手機(jī)踏堡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,277評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來咒劲,“玉大人顷蟆,你說我怎么就攤上這事诫隅。” “怎么了帐偎?”我有些...
    開封第一講書人閱讀 157,221評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵逐纬,是天一觀的道長。 經(jīng)常有香客問我削樊,道長豁生,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,474評(píng)論 1 283
  • 正文 為了忘掉前任漫贞,我火速辦了婚禮甸箱,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘迅脐。我一直安慰自己芍殖,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,570評(píng)論 6 386
  • 文/花漫 我一把揭開白布谴蔑。 她就那樣靜靜地躺著豌骏,像睡著了一般。 火紅的嫁衣襯著肌膚如雪隐锭。 梳的紋絲不亂的頭發(fā)上窃躲,一...
    開封第一講書人閱讀 49,816評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音成榜,去河邊找鬼。 笑死蹦玫,一個(gè)胖子當(dāng)著我的面吹牛赎婚,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播樱溉,決...
    沈念sama閱讀 38,957評(píng)論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼挣输,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了福贞?” 一聲冷哼從身側(cè)響起撩嚼,我...
    開封第一講書人閱讀 37,718評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎挖帘,沒想到半個(gè)月后完丽,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,176評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡拇舀,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,511評(píng)論 2 327
  • 正文 我和宋清朗相戀三年逻族,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片骄崩。...
    茶點(diǎn)故事閱讀 38,646評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡聘鳞,死狀恐怖薄辅,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情抠璃,我是刑警寧澤站楚,帶...
    沈念sama閱讀 34,322評(píng)論 4 330
  • 正文 年R本政府宣布,位于F島的核電站搏嗡,受9級(jí)特大地震影響窿春,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜彻况,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,934評(píng)論 3 313
  • 文/蒙蒙 一谁尸、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧纽甘,春花似錦良蛮、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,755評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至左权,卻和暖如春皮胡,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背赏迟。 一陣腳步聲響...
    開封第一講書人閱讀 31,987評(píng)論 1 266
  • 我被黑心中介騙來泰國打工屡贺, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人锌杀。 一個(gè)月前我還...
    沈念sama閱讀 46,358評(píng)論 2 360
  • 正文 我出身青樓甩栈,卻偏偏與公主長得像,于是被迫代替她去往敵國和親糕再。 傳聞我的和親對(duì)象是個(gè)殘疾皇子量没,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,514評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容