Taro上传图片公用组件

子组件chooseImage

//component/chooseImage/index.js
import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import { AtImagePicker, AtButton } from "taro-ui" class ChooseImage extends Component { constructor() {
super(...arguments);
this.state = ({
files: [],
showUploadBtn:false,
upLoadImg:[]
})
} componentWillMount() {
console.log(this.props.chooseImg)
this.setState({
files: this.props.chooseImg.files,
showUploadBtn:this.props.chooseImgshowUploadBtn,
upLoadImg:this.props.chooseImg.upLoadImg
})
} componentDidShow() { } componentDidHide() { } onChange (v,doType,index) { // doType代表操作类型,移除图片和添加图片,index为移除图片时返回的图片下标
if(doType==='remove'){
this.setState((prevState)=>{
let oldSendImg = prevState.upLoadImg
oldSendImg.splice(oldSendImg[index],) // 删除已上传的图片地址
return ({
files:v,
upLoadImg:oldSendImg
})
},()=>{
const {files} = this.state
//this.setFatherUploadSrc()// 设置删除数据图片地址
if(files.length===){ // 最多三张图片 隐藏添加图片按钮
this.setState({
showUploadBtn:false
})
}else if(files.length===){
this.setState({
upLoadImg:[]
})
}else{
this.setState({
showUploadBtn:true
})
}
})
}else{
v.map((item, index)=>{
if (item.url.indexOf(".pdf") > - || item.url.indexOf(".PDF") > -) {
v[index].url = require("../../assets/images/PDF.png")
}
})
this.setState(()=>{
return ({
files:v
})
},()=>{
const {files} = this.state
if(files.length===){ // 最多三张图片 隐藏添加图片按钮
this.setState({
showUploadBtn:false
})
}else{
this.setState({
showUploadBtn:true
})
}
})
}
}
// 选择失败回调
onFail (mes) {
console.log(mes)
}
// 点击图片回调
onImageClick (index, file) {
let imgs = []
this.state.files.map((item, index) => {
imgs.push(item.file.path)
})
if (imgs[index].indexOf(".pdf") > - || imgs[index].indexOf(".PDF") > -) {
Taro.downloadFile({
url: imgs[index],
success: function (res) {
let filePath = res.tempFilePath
Taro.openDocument({
filePath: filePath,
success: function (res) {
console.log('打开文档成功')
}
})
}
})
}else{
Taro.previewImage({
//当前显示图片
current: imgs[index],
//所有图片
urls: imgs
})
}
}
toUpload = () => {
const { files } = this.state
if(files.length>){
this.props.onFilesValue(files)
const rootUrl = get('rootUrl') // 服务器地址
const cookieData = Taro.getStorageSync('token') // 图片上传需要单独写入token
this.uploadLoader({rootUrl,cookieData,path:files})
}else{
Taro.showToast({
title: '请先点击+号选择图片',
icon: 'none',
duration:
})
}
}
// 上传组件
uploadLoader = (data)=>{
let that = this
let i = data.i ? data.i : // 当前所上传的图片位置
let success=data.success?data.success://上传成功的个数
let fail=data.fail?data.fail:;//上传失败的个数
Taro.showLoading({
title: `正在上传第${i+}张`
})
//发起上传
Taro.uploadFile({
url:data.rootUrl+'/app/index/uploadFile',
header:{
'content-type': 'multipart/form-data',
'cookie':'token='+data.cookieData // 上传需要单独处理cookie
},
name:'file',
filePath:data.path[i].url,
success: (resp) => {
//图片上传成功,图片上传成功的变量+1
let resultData= JSON.parse(resp.data)
if(resultData.code === ""){
success++;
this.setState((prevState)=>{
let oldUpload = prevState.upLoadImg
oldUpload.push(resultData.data)
return({
upLoadImg:oldUpload
})
},()=>{
// setSate会合并所有的setState操作,所以在这里等待图片传完之后再调用设置url方法
/*
* 该处十分重要
**/
//this.setFatherUploadSrc()// 设置数据图片地址字段
})
}else{
fail++;
}
},
fail: () => {
fail++;//图片上传失败,图片上传失败的变量+1
},
complete: () => {
Taro.hideLoading()
i++;//这个图片执行完上传后,开始上传下一张
if(i==data.path.length){ //当图片传完时,停止调用
Taro.showToast({
title: '上传成功',
icon: 'success',
duration:
})
console.log('成功:'+success+" 失败:"+fail);
}else{//若图片还没有传完,则继续调用函数
data.i=i;
data.success=success;
data.fail=fail;
that.uploadLoader(data);
}
}
})
} render() {
const { showUploadBtn } =this.state
return (
<View>
<AtImagePicker
multiple={false}
length={} //单行的图片数量
files={this.state.files}
onChange={this.onChange.bind(this)}
onFail={this.onFail.bind(this)}
onImageClick={this.onImageClick.bind(this)}
showAddBtn={showUploadBtn} //是否显示添加图片按钮
/>
<AtButton type='primary' className='poof_submit_btn' onClick={this.toUpload}>上传图片</AtButton>
</View>
)
}
} export default ChooseImage

父组件home

//pages/home/index.js

import ChooseImage from '../../component/chooseImage'

class Home extends Component {

  constructor() {
super(...arguments);
this.state = ({
chooseImg: {
files: [],
showUploadBtn:true,
upLoadImg:[]
},
files:[],
})
} config = {
navigationBarTitleText: '首页'
} componentWillMount() {
} // 拿到子组件上传图片的路径数组
getOnFilesValue = (value) => {
console.log(value);
this.setState({
files: value
},() => {
console.log(this.state.files)
}) }
render() {
return (
<View className="home">
<ChooseImage chooseImg = {this.state.chooseImg} onFilesValue={this.getOnFilesValue.bind(this)}/>
</View> )
}
} export default Home

如图:

Taro -- 上传图片公用组件的更多相关文章

  1. 微信小程序(14)--上传图片公用组件(父子传参)

    这周整理了一下做微信小程序页面时遇到的一些问题,先说说常见的上传图片吧. 上传图片公用组件 首先要了解的是父子传参. 1.A组件为父组件,B组件为子组件,以下是A组件向B组件传参: 在A组件的json ...

  2. 微信小程序(15)--上传图片公用组件(2)

    接下来开始写写上传图片的公用组件,可以自定义上传几张图片. chooseImage文件夹里面的index.wxml和index.js,涉及图片上传,删除,预览. <view class=&quo ...

  3. React jQuery公用组件开发模式及实现

    目前较为流行的react确实有很多优点,例如虚拟dom,单向数据流状态机的思想.还有可复用组件化的思想等等.加上搭配jsx语法和es6,适应之后开发确实快捷很多,值得大家去一试.其实组件化的思想一直在 ...

  4. vue项目中编写一个图片预览的公用组件

    今天产品提出了一个查看影像的功能需求. 在查看单据的列表中,有一列是影像字段,一开始根据单据号调用接口查看是否有图片附件,如果有则弹出一个全屏的弹出层,如果没有给出提示.而且,从列表进入详情之后,附件 ...

  5. salesforce lightning零基础学习(十五) 公用组件之 获取表字段的Picklist(多语言)

    此篇参考:salesforce 零基础学习(六十二)获取sObject中类型为Picklist的field values(含record type) 我们在lightning中在前台会经常碰到获取pi ...

  6. salesforce lightning零基础学习(十六) 公用组件之 获取字段label信息

    我们做的项目好多都是多语言的项目,针对不同国家需要展示不同的语言的标题.我们在classic中的VF page可谓是得心应手,因为系统中已经封装好了我们可以直接在VF获取label/api name等 ...

  7. 把iview中的table组件写成了一个公用组件,在另一个组件里去引用它的时候rander函数里的this指向不正确

    在vue项目里使用iview制作后台管理系统时,由于有多个页面都需要用到table组件,所以就把table写到了一个公共组件里,在其他页面去引用它,但是这时会发现一个问题,就是render函数里的th ...

  8. Taro音频createVideoContext组件无法调用方法

    用createVideoContext的时候,是在一个组件中 声明后这个实例的方法全部都不能使用了 Taro.createVideoContext('myVideo', this) 需要加上第二个参数 ...

  9. vue 上传图片视频组件,可拍照选择照片,解决苹果手机拍照旋转问题

    1.创建组件components > uploadImg > index.vue <template> <input type="file" name ...

随机推荐

  1. [luogu]P1600 天天爱跑步[LCA]

    [luogu]P1600 [NOIP 2016]天天爱跑步 题目描述 小c同学认为跑步非常有趣,于是决定制作一款叫做<天天爱跑步>的游戏.«天天爱跑步»是一个养成类游戏,需要玩家每天按时上 ...

  2. (42)嵌入式项目中常用到的C语言技能总结

    嵌入式项目中常用到的C语言技能 1.指针 .结构体. 枚举. 联合.数组.字符串.链表七个专题 2.结构体指针.结构体的多重嵌套[结构体中嵌套结构体.结构体中嵌套枚举.联合体.结构体中嵌套函数指针.一 ...

  3. A - Biorhythms (第三周)

    A - Biorhythms 链接:https://vjudge.net/contest/154063#problem Description 人生来就有三个生理周期,分别为体力.感情和智力周期,它们 ...

  4. Mybatis一对一关联查询

    有两张表,老师表teacher和班级表class,一个class班级对应一个teacher,一个teacher对应一个class 需求是根据班级id查询班级信息(带老师的信息) 创建teacher和c ...

  5. iOS环境搭建

    Xcode安装 一定要在App Store上下载XCode . git config常用配置 设置lg命令 查看分支图 git config --global alias.lg "log - ...

  6. python实现RESTful服务(基于flask)

    https://www.jianshu.com/p/6ac1cab17929 http://www.pythondoc.com/flask/quickstart.html 在java中调用python ...

  7. TypeError: list indices must be integers or slices, not str

    错误如下: TypeError: list indices must be integers or slices, not str 错误代码块: aa是一组list套dict数据 函数insert接收 ...

  8. 阶段1 语言基础+高级_1-3-Java语言高级_1-常用API_1_第3节 Random类_8-Random概述和基本使用

    用来产生随即数字 构造方法有一个是为空的 每次运行数值都不一样

  9. Java各类型占字节数

    byte 1字节short 2字节int 4字节long 8字节float 4字节double 8字节char 2字节boolean 1字节 其中,换算关系: 1GB=1024MB 1MB=1024K ...

  10. 字符串 映射相应的 函数 字符串驱动技术—— MethodAddress , MethodName , ObjectInvoke

    http://blog.csdn.net/qustdong/article/details/7267258 字符串驱动技术—— MethodAddress , MethodName , ObjectI ...