2017-07-18 37 views
0

此处的代码旨在将以multipart/form-data(文件已成功在多方模块中解析的文件)上载的图像保存到Amazon S3,然后获取所有图像图像桶URL并将其保存到mongodb中的imageUrl数组字段。但是,imageUrl总是空的。 我发现在loopwithcb函数中imageUrl具有正确的URL。 在保存后的回调函数中,imageUrl为空。我认为这是异步的问题,但仍然无法弄清楚。任何想法都会有帮助。如何在使用nodejs在S3中保存所有图像后获取网址

//save images to S3 
var i=-1; 
var imageUrl =[]; 
function loopwithcb(afterSave){ 
    Object.keys(files.files).forEach(function(){ 
    i=i+1; 
    var myFile = files.files[i]; 
    var fileName = Date.now()+myFile.originalFilename; 
    s3Client.upload({ 
     Bucket: bucket, 
     Key: fileName, 
     ACL: 'public-read', 
     Body: fs.createReadStream(myFile.path) 
     //ContentLength: part.byteCount 
    }, function (err, data) { 
     if (err) { 
      //handle error 
     } else { 
      //handle upload complete 
      var s3url = "https://s3.amazonaws.com/" + bucket + '/' + fileName; 
      imageUrl.push(s3url); 
      console.log('imageurl:'+ imageUrl); 
      //delete the temp file 
      fs.unlink(myFile.path); 
      console.log('url:' + imageUrl);        
     } 
    }); 
    }); 
    afterSave(); 
} 
function afterSave(){ 
    console.log('i:'+ i); 
    console.log('outside print imageurl:'+ imageUrl); 
    Listing.create({ 
     title : fields.ltitle, 
     type : 'newlist', 
     description : fields.lbody, 
     image : imageUrl 
     }, function (err, small) { 
     if (err) return handleError(err); 
     // saved! 
     console.log(small); 
     console.log('listingId:' + ObjectId(small._id).valueOf()); 
     //res.json(small); 
    }); 
} 
loopwithcb(afterSave); //call back 

回答

0

改变了一些代码的一部分,现在它可以打印出正确的IMAGEURL。但是,新代码不会将文件上传到AWS S3。发现这个解决方案(async for loop in node.js)正是我想要的。

function loopwithcb(afterSave){ 
    Object.keys(files.files).forEach(function(){ 
    i=i+1; 
    var myFile = files.files[i]; 
    var fileName = Date.now()+myFile.originalFilename; 
    var saved = s3Client.upload({ 
     Bucket: bucket, 
     Key: fileName, 
     ACL: 'public-read', 
     Body: fs.createReadStream(myFile.path) 
     //ContentLength: part.byteCount 
    });  
    if (saved.err) { 
     //handle error 
    } else { 
     //handle upload complete 
     var s3url = "https://s3.amazonaws.com/" + bucket + '/' + fileName; 
     imageUrl.push(s3url); 
     console.log('imageurl:'+ imageUrl); 
     //delete the temp file 
     fs.unlink(myFile.path); 
     console.log('url:' + imageUrl);        
    }  
    }); 
    afterSave(); 
} 
相关问题