React-Native:将多个图像上传到服务器

时间:2019-06-10 17:31:31

标签: react-native react-native-image react-native-image-picker

我创建了供用户拍摄1张照片,然后将其上传到我的Firebase数据库的功能。但是,我正在努力:

1)允许用户拍摄多张照片(比方说6)。我可以使用某些功能来使相机保持打开状态,以允许用户继续拍摄直到达到6张限制吗?

2)捆绑所有图像并将其作为一个组上传到Firebase数据库中。现在,我只是在定义存储路径。

我提供了我要使用的5个功能:

1)允许用户从相机拍摄照片(findNewImage)

2)上传(uploadPublish)之前,请确保图片中也有标题

3)根据图像的格式(.png,.jpeg等)(uploadImage)创建文件路径

4)使用“ uploadImage”(completeUploadBlob)生成的文件路径将图像上传到Firebase

5)将图像与实时数据库链接(processUpload)

    findNewImage = async () => {
        this._checkPermissions();

        let result = await ImagePicker.launchCameraAsync({
            mediaTypes: "Images",
            allowsEditing: true,
            quality: 1
        });

        console.log("image picked is = result = ", result);

        if (!result.cancelled) {

            console.log("upload image");
            this.setState({
                imageSelected: true,
                imageId: this.uniqueId(),
                uri: result.uri
            });

        } else {

            console.log("cancel");
            this.setState({
                imageSelected: false
            });

        }
    };

    uploadPublish = () => {
        if (this.state.uploading == false) {

            if (this.state.caption != "") {
                //uploading image to firebase, as we have img with caption
                this.uploadImage(this.state.uri);
            } else {
                alert("Please enter caption for your photo before posting!");
            }

        } else {

            console.log("Ignoring click more than once.");

        }
    };

    // this is main function to upload upload img
    uploadImage = async uri => {
        let that = this;
        let userid = f.auth().currentUser.uid;
        let imageId = this.state.imageId; // imgId = uniqueIdGenerated()

        // check file extension ofo uploaded img
        let re = /(?:\.([^.]+))?$/; // filename, regular-expression
        let ext = re.exec(uri)[1]; // extension

        this.setState({
            currentFileType: ext,
            uploading: true
        });

        let FilePath = imageId + "." + that.state.currentFileType;

        const oReq = new XMLHttpRequest();
        oReq.open("GET", uri, true);
        oReq.responseType = "blob";
        oReq.onload = () => {
            const blob = oReq.response;
            //Call function to complete upload with the new blob to handle the uploadTask.
            this.completeUploadBlob(blob, FilePath);
        };

        oReq.send();
    };

    completeUploadBlob = (blob, FilePath) => {
        let that = this;
        let userid = f.auth().currentUser.uid;
        let imageId = this.state.imageId;

        let uploadTask = storage
        .ref("user/" + userid + "/img")
        .child(FilePath)
        .put(blob);

        uploadTask.on(
            "state_changed",
            snapshot => {
                let progress = ((snapshot.bytesTransferred / snapshot.totalBytes) * 100).toFixed(0);

                console.log("Upload is " + progress + "% completed.");

                that.setState({
                    progress: progress
                });
            },
            err => { console.log("error with upload - " + err); },

            // now upload is completed,
            () => {
                that.setState({
                    progress: 100
                });

                uploadTask.snapshot.ref.getDownloadURL().then(downloadURL => {
                    console.log("downloadURL is =", downloadURL);
                    that.processUpload(downloadURL);
                });
            }
        );
    };

    processUpload = imageUrl => {
        // set needed info of user

        //Set needed info
        let imageId = this.state.imageId;
        let userId = f.auth().currentUser.uid;
        let dateTime = Date.now();
        let caption = this.state.caption;
        let timestamp = Math.floor(dateTime / 1000);

        // we have uploaded img to storage, but we have to link that url with realtime-db
        // photo-json = author, caption, posted-timestamp, urlofimg

        let photoObj = {
            author: userId,
            caption: caption,
            posted: timestamp,
            url: imageUrl
        };

        // now, add info to realtime-db in two locations. as feed & profile
        // add data to photo-obj and user-object

        console.log("f.auth().currentUser.uid ", f.auth().currentUser.uid);
        // first to add photo to main feed of photos    database.ref("/photos/" + imageId).set(photoObj);

        // add photosobj to user-json as well.

        database.ref("/users/" + userId + "/photos/" + imageId).set(photoObj);

        // photo was not uploaded automatically to photos collection, on adding it to user's collection
        // then, manually adding that entry in photo collection after adding to users/userId/photosColln
        database.ref("/photos/" + imageId).set(photoObj);
        //  for debugging to see why image is not uploaded to database
        console.log("upload_226, userId =", userId);
        console.log("upload_226, imageId =", imageId);
        console.log("upload_226, photoObj is \n", photoObj);

        alert("Image Successfully Uploaded. Refresh Feed to View.");
        // after uploading photo, reset photo-attribute/ states

        this.setState({
            uploading: false,
            imageSelected: false,
            caption: "",
            uri: ""
        });
    };

预先感谢

0 个答案:

没有答案