{this.setState({ uploadImgs: urls}) }}src={uploadImgs}/>”를 호출하여 이미지를 선택하고 업로드할 수 있습니다."/> {this.setState({ uploadImgs: urls}) }}src={uploadImgs}/>”를 호출하여 이미지를 선택하고 업로드할 수 있습니다.">

 >  기사  >  웹 프론트엔드  >  반응에서 이미지 선택을 구현하는 방법

반응에서 이미지 선택을 구현하는 방법

藏色散人
藏色散人원래의
2023-01-19 14:21:401475검색

반응에서 이미지 선택을 구현하는 방법: 1. 가져오기를 사용하여 "react-native-image-picker" 플러그인을 도입합니다. 2. "{this.setState({uploadImgs: urls})}}src=를 사용합니다. {uploadImgs}/> ;" 이미지를 선택하고 업로드하려면 호출하세요. ={6}onchange={urls>

반응에서 이미지 선택을 구현하는 방법

이 튜토리얼의 운영 환경: Windows 10 시스템, 반응 버전 18.0.0, Dell G3 컴퓨터.

반응에서 이미지 선택을 구현하는 방법은 무엇입니까?

React 네이티브 Qiniu 업로드 + 로컬 이미지 선택

참고:

react-native-image-crop-picker图片选择并裁减 //这个看需求使用
https://github.com/ivpusic/react-native-image-crop-picker
react-native-image-picker图片选择
https://github.com/react-native-image-picker/react-native-image-picker
react-native-qiniu
https://github.com/buhe/react-native-qiniu

다중 이미지 업로드 기능만 원해서 간단히 작성하겠습니다

Effect

반응에서 이미지 선택을 구현하는 방법

업로드 상태

반응에서 이미지 선택을 구현하는 방법

업로드 중 상태

단계

1. 휴대폰 사진 및 동영상 선택 기능

react-native-image-picker 플러그인을 사용하세요

yarn add-native-image-picker가 필요합니다.

import {launchCamera, launchImageLibrary, ImageLibraryOptions, PhotoQuality} from 'react-native-image-picker';
/**
 * 从相册选择图片;
 * sourceType: 'camera'  打开相机拍摄图片
**/
export async function chooseImage(options: {
  count?: number,
  quality?: PhotoQuality
  sourceType?: 'camera',  //默认'album'
} = {}) {
  return new Promise<any>(async(resolve, reject) => {
    const Opts: ImageLibraryOptions = {
      mediaType: &#39;photo&#39;,
      quality: options.quality || 1,
      selectionLimit: options.count || 1
    };
    const result = options.sourceType == &#39;camera&#39;? 
      await launchCamera(Opts) : 
      await launchImageLibrary(Opts);
    resolve(result)
  })
}
/**
 * 从相册选择视频;
 * sourceType: &#39;camera&#39;  打开相机拍摄视频
**/
export async function chooseVideo(options: {
  count?: number,
  quality?: &#39;low&#39; | &#39;high&#39;
  sourceType?: &#39;camera&#39;,  //默认&#39;album&#39;
} = {}) {
  return new Promise<any>(async(resolve, reject) => {
    const Opts: ImageLibraryOptions = {
      mediaType: &#39;video&#39;,
      videoQuality: options.quality,
      selectionLimit: options.count || 1
    };
    const result = options.sourceType == &#39;camera&#39;? 
      await launchCamera(Opts) : 
      await launchImageLibrary(Opts);
    resolve(result)
  })
}

2. 세븐카우 파일 업로드 기능

class qiniuUpload {
  private UP_HOST = &#39;http://upload.qiniu.com&#39;;
  // private RS_HOST = &#39;http://rs.qbox.me&#39;;
  // private RSF_HOST = &#39;http://rsf.qbox.me&#39;;
  // private API_HOST = &#39;http://api.qiniu.com&#39;;
  public upload = async(uri:string, key:string, token:string) => {
    return new Promise<any>((resolve, reject) => {
      let formData = new FormData();
      formData.append(&#39;file&#39;, {uri: uri, type: &#39;application/octet-stream&#39;, name: key});
      formData.append(&#39;key&#39;, key);
      formData.append(&#39;token&#39;, token);
    
      let options:any = {
        body: formData,
        method: &#39;post&#39;,
      };
      fetch(this.UP_HOST, options).then((response) => {
        resolve(response)
      }).catch(error => {
        console.error(error)
        resolve(null)
      });  
    })
  }
   //...后面再加别的功能
}
const qiniu = new qiniuUpload();
export default qiniu;
import qiniu from &#39;@/modules/qiniu/index&#39;
...
  /**
   * 上传视频图片
   */
  uploadFile: async (filePath: string) => {
    const res = await createBaseClient(&#39;GET&#39;, &#39;/v1/file&#39;)();  //这是接口请求方法,用来拿后端的七牛token、key
    
    if( !res ) {
      return res;
    }
    const { key, token } = res;
    const fileSegments = filePath.split(&#39;.&#39;);
    const fileKey = key + &#39;.&#39; + fileSegments[fileSegments.length - 1];
    try {
      const result = await qiniu.upload(filePath, fileKey, token)
      if(result && result.ok) {
        return {
          url: ASSET_HOST + &#39;/&#39; + fileKey,  //ASSET_HOST是资源服务器域名前缀
        };
      }else {
        return null
      }
    } catch (error) {
      return null;
    }
  },
...

3. 다중 이미지 업로드 컴포넌트 캡슐화

(베이스, 이미지, 액션시트 모두 여기에 캡슐화되어 있어 상황에 따라 조정 필요)

import React from &#39;react&#39;
import {
  ViewStyle,
  StyleProp,
  ImageURISource,
  ActivityIndicator
} from &#39;react-native&#39;
import Base from &#39;@/components/Base&#39;;
import { Image, View, Text } from &#39;@/components&#39;;   //Image封装过的,所以有些属性不一样
import ActionSheet from "@/components/Feedback/ActionSheet";  //自己封装
import styles from &#39;./styleCss&#39;;  //样式就不放上来了
interface Props {
  type?: &#39;video&#39;
  src?: string[]
  count?: number
  btnPath?: ImageURISource
  style?: StyleProp<ViewStyle>
  itemStyle?: StyleProp<ViewStyle>
  itemWidth?: number
  itemHeight?: number  //默认正方形
  onChange?: (e) => void
}
interface State {
  imageUploading: boolean
  images: string[]
}
/**
 * 多图上传组件
 * * type?: &#39;video&#39;
 * * src?: string[]   //图片数据,可用于初始数据
 * * count?: number    //数量
 * * btnPath?: ImageURISource   //占位图
 * * itemStyle?: item样式,width, height单独设
 * * itemWidth?: number
 * * itemHeight?: number  //默认正方形
 * * onChange?: (e:string[]) => void
**/
export default class Uploader extends Base<Props, State> {
  public state: State = {
    imageUploading: false,
    images: []
  };
  public didMount() {
    this.initSrc(this.props.src)
  }
  public componentWillReceiveProps(nextProps){
    if(nextProps.hasOwnProperty(&#39;src&#39;) && !!nextProps.src){
      this.initSrc(nextProps.src)
    }
  }
  /**
   *初始化以及改动图片
  **/
  private initSrc = (srcProp:any) => {
    if(!this.isEqual(srcProp, this.state.images)) {
      this.setState({
        images: srcProp
      })
    }
  }
  
  public render() {
    const { style, btnPath, count, itemStyle, itemWidth, itemHeight, type } = this.props;
    const { imageUploading, images } = this.state;
    let countNumber = count? count: 1
    return (
      <React.Fragment>
        <View style={[styles.uploaderBox, style]}>
          {images.length > 0 && images.map((res, ind) => (
            <View style={[styles.item, itemStyle]} key={res}>
              <View style={styles.imgItem}>
                <Image
                  source={{uri: res}}
                  width={this.itemW}
                  height={this.itemH}
                  onPress={() => {
                    this.singleEditInd = ind;
                    this.handleShowActionSheet()
                  }}
                />
                <Text style={styles.del} onPress={this.handleDelete.bind(null, ind)}>删除</Text>
              </View>
            </View>
          ))}
          {images.length < countNumber  &&
            <View style={[styles.item, itemStyle]}> 
              {imageUploading? (
                <View style={[{
                  width: this.itemW,
                  height: this.itemH,
                }, styles.loading]}>
                  <ActivityIndicator size={this.itemW*0.4}></Loading>
                  <Text style={{
                    fontSize: 14,
                    color: &#39;#888&#39;,
                    marginTop: 5
                  }}>
                    上传中...
                  </Text>
                </View>
              ): (
                <View style={styles.btn}>
                  <Image
                    source={btnPath || this.assets.uploadIcon}
                    width={this.itemW}
                    height={this.itemH}
                    onPress={() => {
                      this.singleEditInd = undefined;
                      this.handleShowActionSheet()
                    }}
                  />
                </View>
              )}
              
            </View>
          }
          
        </View>
        <ActionSheet
          name="uploaderActionSheet"
          options={[{
            name: type == &#39;video&#39;? &#39;拍摄&#39;: &#39;拍照&#39;,
            onClick: () => {
              if(type == &#39;video&#39;) {
                this.handleChooseVideo(&#39;camera&#39;)
              }else if(this.singleEditInd !== undefined) {
                this.handleChooseSingle(&#39;camera&#39;)
              }else {
                this.handleChooseImage(&#39;camera&#39;)
              }
            }
          }, {
            name: &#39;相册&#39;,
            onClick: () => {
              if(type == &#39;video&#39;) {
                this.handleChooseVideo()
              }else if(this.singleEditInd !== undefined) {
                this.handleChooseSingle()
              }else {
                this.handleChooseImage()
              }
            }
          }]}
        ></ActionSheet>
      </React.Fragment>
    );
  }
  private get itemW() {
    return this.props.itemWidth || 92
  }
  private get itemH() {
    return this.props.itemHeight || this.itemW;
  }
  
  private isEqual = (firstValue, secondValue) => {
    /** 判断两个值(数组)是否相等 **/
    if (Array.isArray(firstValue)) {
      if (!Array.isArray(secondValue)) {
        return false;
      }
      if(firstValue.length != secondValue.length) {
        return false;
      }
      return firstValue.every((item, index) => {
        return item === secondValue[index];
      });
    }
    return firstValue === secondValue;
  }
  private handleShowActionSheet = () => {
    this.feedback.showFeedback(&#39;uploaderActionSheet&#39;);  //这是显示ActionSheet选择弹窗。。。
  }
  private handleChooseImage = async (sourceType?: &#39;camera&#39;) => {
    const { imageUploading, images } = this.state;
    const { count } = this.props
    if (imageUploading) {
      return;
    }
    let countNumber = count? count: 1
    const { assets } = await this.interface.chooseImage({  //上面封装的选择图片方法
      count: countNumber,
      sourceType: sourceType || undefined,
    });
    
    if(!assets) {
      return;
    }
    this.setState({
      imageUploading: true,
    });
    
    let request:any = []
    assets.map(res => {
      let req = this.apiClient.uploadFile(res.uri)   //上面封装的七牛上传方法
      request.push(req)
    })
    Promise.all(request).then(res => {
      let imgs:any = []
      res.map((e:any) => {
        if(e && e.url){
          imgs.push(e.url)
        }
      })
      imgs = [...images, ...imgs];
      this.setState({
        images: imgs.splice(0,countNumber),
        imageUploading: false,
      },
        this.handleChange
      );
    })
    
  }
  private singleEditInd?: number;  //修改单个时的索引值
  private handleChooseSingle = async(sourceType?: &#39;camera&#39;) => {
    let { imageUploading, images } = this.state;
    if (imageUploading) {
      return;
    }
    
    const { assets } = await this.interface.chooseImage({   //上面封装的选择图片方法
      count: 1,
      sourceType: sourceType || undefined,
    });
    if(!assets) {
      return;
    }
    this.setState({
      imageUploading: true,
    });
    const res = await this.apiClient.uploadFile(assets[0].uri)   //上面封装的七牛上传方法
    if(res && res.url && this.singleEditInd){
      images[this.singleEditInd] = res.url
    }
    this.setState({
      images: [...images],
      imageUploading: false,
    },
      this.handleChange
    );
    
  }
  private handleChooseVideo = async(sourceType?: &#39;camera&#39;) => {
    const { onChange } = this.props
    let { imageUploading } = this.state;
    if (imageUploading) {
      return;
    }
    
    const { assets } = await this.interface.chooseVideo({
      sourceType: sourceType
    });
    if(!assets) {
      return;
    }
    this.setState({
      imageUploading: true,
    });
    const res = await this.apiClient.uploadFile(assets[0].uri)   //上面封装的七牛上传方法
    if(res && res.url){
      //视频就不在组件中展示了,父组件处理
      if(onChange) {
        onChange(res.url)
      }
    }
    this.setState({
      imageUploading: false,
    });
    
  }
  private handleDelete = (ind:number) => {
    let { images } = this.state
    images.splice(ind,1)
    this.setState({
      images: [...images]
    },
      this.handleChange
    )
  }
  private handleChange = () => {
    const { onChange } = this.props
    const { images } = this.state
    if(onChange) {
      onChange(images)
    }
  }
}

4.

추천 학습: "

react 비디오 튜토리얼

위 내용은 반응에서 이미지 선택을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.