2017-08-10 262 views
1

我通过我的CMS提交表单,其中包含一个文件选择器&一些文本。该代码运行&一个对象在我的S3帐户中以正确的名称创建,但已损坏。例如,我正在上传JPG图像,但是当我在s3仪表板中查看它们时,我只看到一个黑屏。Node.js上传到亚马逊S3的作品,但文件损坏

任何帮助,非常感谢。

我的HTML表单:

<form enctype="multipart/form-data" action="updateSchedule" method="POST"> 
 
     <input type="file" name="schedulepicture" id="schedulepicture"> 
 
     <textarea rows="4" cols="50" id="ScheduleText" name="ScheduleText" maxlength="2000">      <button type="submit" id="updateschedulebutton">Update</button> 
 
</form>

我的Node.js脚本:

router.post('/updateschedule', isLoggedIn, upload.single('schedulepicture'), function(req, res) { 
 
    var scheduleImageToUpload; 
 

 
    //Check if image was uploaded with the form & process it 
 
    if (typeof req.file !== "undefined") { 
 

 
    //Create Amazon S3 specific object 
 
    var s3 = new aws.S3(); 
 
    
 
    //This uploads the file but the file cannot be viewed. 
 
    var params = { 
 
     Bucket: S3_BUCKET, 
 
     Key: req.file.originalname, //This is what S3 will use to store the data uploaded. 
 
     Body: req.file.path, //the actual *file* being uploaded 
 
     ContentType: req.file.mimetype, //type of file being uploaded 
 
     ACL: 'public-read', //Set permissions so everyone can see the image 
 
     processData: false, 
 
     accessKeyId: S3_accessKeyId, 
 
     secretAccessKey: S3_secretAccessKey 
 
    } 
 

 
    s3.upload(params, function(err, data) { 
 
     if (err) { 
 
     console.log("err is " + err); 
 
     } 
 
     res.redirect('../adminschedule'); 
 
    }); 
 
    } 
 
});

回答

1

我相信你需要传递一个流而不是文件路径,你可以像这样使用fs.createReadStream:

router.post('/updateschedule', isLoggedIn, upload.single('schedulepicture'), function(req, res) { 
    var scheduleImageToUpload; 

    //Check if image was uploaded with the form & process it 
    if (typeof req.file !== "undefined") { 

    //Create Amazon S3 specific object 
    var s3 = new aws.S3(); 
    var stream = fs.createReadStream(req.file.path) 

    //This uploads the file but the file cannot be viewed. 
    var params = { 
     Bucket: S3_BUCKET, 
     Key: req.file.originalname, //This is what S3 will use to store the data uploaded. 
     Body: stream, //the actual *file* being uploaded 
     ContentType: req.file.mimetype, //type of file being uploaded 
     ACL: 'public-read', //Set permissions so everyone can see the image 
     processData: false, 
     accessKeyId: S3_accessKeyId, 
     secretAccessKey: S3_secretAccessKey 
    } 

    s3.upload(params, function(err, data) { 
     if (err) { 
     console.log("err is " + err); 
     } 
     res.redirect('../adminschedule'); 
    }); 
    } 
});