使用带有express的节点将文件上传到aws S3

时间:2018-01-26 01:17:28

标签: javascript node.js express amazon-s3

我在html中有一个简单的表单,通过将图像发送到node.js中的服务并使用express,图像到达服务没有问题,但我需要把它上传到亚马逊s3,这就是我不能做的,我不知道如何将图像从index.js传递到将我的服务连接到亚马逊并上传图像的控制器。

这是我的html表单:

<html>
 <head>
    <meta charset="utf-8">
    <title>Subir</title>
 </head>
 <body>
  <form method="POST" action="http://localhost:3004/sendFile">
    <input type="file" name="imagen" id="imagen">
     <br>
     <br>
    <input type="submit" value="Subir">
  </form>
 </body>
</html>

这里是我的index.js

 import express from 'express';
 import { userInfo } from './controllers/validator';
 var app = express();
 import path from 'path';
 import adminFile from './services/adminFile';
 import logger from './core/logger';

 var bodyParser = require('body-parser');
 var app     = express();

app.use(bodyParser.urlencoded({ extended: true }));

 app.set("port", 3004);

 app.post('/sendFile', (req, res) => {
 adminFile.adminFile
 });
  app.listen(3004, function() {
  logger.log('info','File-Manager corriendo en puerto'+ 
  app.get('port'));
 });

这是我的控制器:

  var express = require('express')
  , router = express.Router()
  , aws = require('aws-sdk')

   const sendQuotes = (req, res, next) => {
   logger.log('info', "Entrando a enviar cotizaciones");
    if (!get(req, 'body.data')) {
    return res.status(422).send();
    next();
   }

  var AWS_ACCESS_KEY = 'my_access_key'
  var AWS_SECRET_KEY = 'my_secret_key'
  var S3_BUCKET = 'my_bucket'

  router.get('/sendFile', function(req, res) {
   aws.config.update({accessKeyId: AWS_ACCESS_KEY, secretAccessKey: 
  AWS_SECRET_KEY});

  var s3 = new aws.S3()
  var options = {
Bucket: S3_BUCKET,
Key: req.query.file_name,
Expires: 60,
ContentType: req.query.file_type,
ACL: 'public-read'
}

  s3.getSignedUrl('putObject', options, function(err, data){
   if(err) return res.send('Error with S3')

   res.json({
   signed_request: data,
    url: 'https://s3.amazonaws.com/' + S3_BUCKET + '/' + 
    req.query.file_name
    })
  })
})

  module.exports = router

0 个答案:

没有答案