httpUploadProgress无法正常工作缓冲区数据?

时间:2017-01-23 11:23:29

标签: javascript node.js express amazon-s3 foreach

我是节点js / express的新手。我正在尝试使用cloudfront和s3 bucket制作多个图片上传应用。我想为用户显示进度条我正在使用socket io。照片上传进度将在loop.but问题是当照片上传开始时,它总是显示100%完成而不是从头开始。不认为上传完成它不是,我的文件是20MB。我不知道&#39发生的事情我错过了什么

这是我的代码

app.post('/posttodb',(req,res) => {

   let isLoggedIn = req.cookies['check'];
   let token = req.cookies['peace'];
    const bucketName = 'awsBucketName';
    console.log(isLoggedIn);
    if(isLoggedIn == "true"){
        if(token){
            jwt.verify(token,JWTPASS,(err,decode) => {

                if(err){
                    console.log(err)
                    res.json({error:true})
                }else{
                    console.log('========================>',decode)

                   let postOwneranme = decode.user.username;
                    let postTags = req.body.data.postTags;
                    let photosBlob = req.body.data.photos;
                    let postId = req.body.data.postId;
                    let nepostAwsPhots = [];
                    let OwnerPic = decode.user.propic;
                    let postOwnerFullName = decode.user.name;
                    let isMature = req.body.data.isMature;
                    let postThumbUrl = req.body.data.thumnailUrl;
                    let time = new Date();

                    let tagSlug  = req.body.data.tagSlug;


                    function savetodb() {
                        console.log('Inserting all into DB');
                        r.connect({db:'image'}).then(conn => {

                            r.table('posts').insert({postId:postId,username:postOwneranme,tag:postTags,postUrlsAndCaptions:nepostAwsPhots,comments:[],postOwnerPic:OwnerPic,likesCount:0,whoLikedIt:[],views:0,postedTime:time,postOwnerFullName:postOwnerFullName,isMature:isMature,thumNailUrl:postThumbUrl,tagSlug:tagSlug}).run(conn).then(response => {
                                console.log(response)

                                if(response.inserted > 0){
                                    console.log('Done Bro')
                                    res.json({okva:true,postId:postId,username:postOwneranme})
                                }else{
                                    res.json({okva:false})
                                }
                            })
                        })



                    }
                    function seemsToHaveNetworkProblem() {
                        res.json({okva:false,message:"Seems To Have Network Problem"})
                    }


                        forEachOf(photosBlob,(value,key,callback) => {
                            console.log(value.id);
                            let newImageUriWillBe = value.blobData;
                            let newImageNamewillBe = value.id;
                            let imageType = value.ImageType;
                            let caption = value.caption;
                            console.log(imageType)
                            let buf = new Buffer(newImageUriWillBe.replace(/^data:image\/\w+;base64,/, ""),'base64');
                            s3.createBucket({Bucket:bucketName},() => {
                                let params = {Bucket: bucketName, Key: postOwneranme+'/'+newImageNamewillBe, Body: buf,ContentType:imageType,ContentLength:buf.length,ACL:'public-read'};
                                s3.upload(params,(err,data) => {
                                    if(err){
                                        callback(err);
                                    }else{
                                        // console.log("Successfully uploaded data to " + bucketName + "/" + id);
                                        // console.log(`https://s3.amazonaws.com/${bucketName}/${username}/${id}`);
                                        let response = {
                                            picUrl:`https://s3.amazonaws.com/${bucketName}/${postOwneranme}/${newImageNamewillBe}`,
                                            cation:caption

                                        }


                                        nepostAwsPhots.push(response);


                                        callback()

                                        // console.log(nepostAwsPhots)
                                        res.writeHead(200, {'content-type': 'text/plain'});
                                        res.end('Ok');



                                    }
                                })
                               //Problem Comes here

                                    .on('httpUploadProgress', function(evt) {

                                    let per = Math.round((evt.loaded * 100) / evt.total)
                                    console.log('Progress:',per);

                                    Socket.emit('Scoket',{proccesing:per})



                                    })


                            });
                     },(err) => {
                        if(err){
                            console.log("From Node Loop error",err);
                            seemsToHaveNetworkProblem()
                        }else {
                            savetodb()
                        }
                    })


                }
            })
        }else {
            res.json({error:true});
            console.log('OMG')
        }
    }else{
        res.json({error:true});
        console.log('OMG')
    }





});

2 个答案:

答案 0 :(得分:1)

  

首先检查更新 是否最新版本,然后尝试使用此修改代码:

.on('httpUploadProgress',function(progress) {
    console.log(Math.round(progress.loaded/progress.total*100)+ '% done');
    });

答案 1 :(得分:0)

我不确定发生了什么,但我认为这个问题有助于解决问题。虽然,其中使用的变量来自另一个类似的来源。尝试采用这种方法。

ss(socket).emit('strimage', stream, {size: file.size,name: fileName,email: emailid});
//initialize var to 0
                    var blobStream = ss.createBlobReadStream(file);
                    var size = 0;
                    var uploadedSize;
                    blobStream.on('data', function(chunk) {
                      size += chunk.length;
//try giving an upload size
                        uploadedSize = Math.floor(size / file.size * 100)
                      console.log(uploadedSize + '%');
                        if (uploadedSize == 100) {
                            console.log("inside uploadedSize");
                            socket.emit('uploadcomplete', data);
                        }
                    });

                    blobStream.pipe(stream);