Получение неопределенного имени файла, типа файла при загрузке файлов в AWS S3 - PullRequest
0 голосов
/ 14 сентября 2018

Что я пытаюсь сделать:
Загрузка файла с помощью AWS S3, а затем взятие имени файла и типа файла и размещение его в конце URL-адреса для сохранения его в sql, чтобы каждый раз, когда человек регистрируетсяв, он вытянет изображение вверх по URL-адресу изображения пользователя.

Проблема:
Не загружается и не распознается файл в имени файла или типе файла.Подходя к неопределенному типу файла и имени файла в URL и подписанномуURL

Код для моего fileUploadService.js, используемого в Node.js, показан ниже.

getSignedURL выглядит следующим образом:
https://sabio -training.s3.us-west-2.amazonaws.com / C56 / filename /? AWSAccessKeyId = AKIAJF53EJKW7SJUV55Q & Content-Type = filetype & Expires= 1536877443 & Signature = WxSvLSzfyZKDRN9LawVOwj1ayVY% 3D & x-amz-acl = public-read

URL выглядит следующим образом:
https://sabio -training.s3.amazonaws.com / C56 / filename/ filetype

 const aws = require('aws-sdk');
aws.config.region = 'us-west-2';
aws.config.update({ accessKeyId: '', secretAccessKey: '' });
const PROFILE_S3_LINK = "https://sabio-training.s3.amazonaws.com/";

module.exports = {
  getUrl: getUrl
}

function getUrl(req, res) {
  
  const s3 = new aws.S3();
  const fileName = 'C56/'+"filename"+'/' ;  //hardcoded filename and filetype for it to work. 
  const fileType = "filetype";              //How to take filename from uploaded file to insert into "fileName" along with the "filetype"?
  const s3Params = {                        
    Bucket: 'sabio-training',                                                                       
    Key: fileName,                          
    Expires: 3000,
    ContentType: fileType,
    ACL: 'public-read'
  };

  s3.getSignedUrl('putObject', s3Params, (err, data) => {
    if (err) {
      console.log(err);
      return res.end();
    }
    const returnData = {
      signedRequest: data,
      url: `${PROFILE_S3_LINK}${fileName}${fileType}` //unsigned URL
    };
    res.write(JSON.stringify(returnData));
    res.end();
  });
}

=========================================================================
fileUploadRoute.js

const router = require("express").Router();
const fileUploadController = require("../controllers/fileUploadController")

router.put("/", fileUploadController.getUrl);

module.exports = router;

==========================================================================
fileUploadController.js

const fileUploadService = require('../services/fileUploadService')
const responses = require("../models/responses");

module.exports = {
    getUrl: getUrl
}

function getUrl(req, res) {
    fileUploadService.getUrl(req, res)
        .then(response => {
            res.send(response)
        })
        .catch(error => {
            res.send(error)
        })
}
===========================================================================
index.js in node portion


const router = require("express").Router();
const pogsRoutes = require("./pogs.routes");
const userFromJWT = require("../filters/jwt.user");
const validateUser = require("../filters/validate.user");
const testRoutes = require("./test.routes");
const profileRoute = require("../profile/profileRoute");
const fileUploadRoute = require("../fileUpload/fileUploadRoute")

module.exports = router;
// router.use("/api/profilePage", profileRoute)

router.use("/api/pogs", pogsRoutes);
router.use("/api/upload", fileUploadRoute)
router.use("/api/profilePage", profileRoute)
// -----------------------------------
// Authenticated routes go below this:
// -----------------------------------

router.use(userFromJWT);
router.use(validateUser);

router.use("/api/test", testRoutes); // TODO: remove this before delivery to the client

============================================================================
USED IN REACT

Axios pulled from profile page 

handleClickUpload = evt => {
        evt.preventDefault()
        console.log("RESULT : ", this.state);
        // var file = evt.target.files[0]; <-- havent used this yet but I know its for upload


        axios.put(`${NODE_API_URL}/api/upload`, {
                // f:file
        })
        .then(response =>{
                console.log(
                response,"URL SIGNED REQUEST : ",response.data.signedRequest, " URL : ",response.data.url
                )
        })
        .catch(error => {
                console.log(error);
        })
}

Upload button and file upload portion inside profile page

               <div method="post" encType="multipart/form-data" action="/">
        <input type="file" name="fileName" className="btn" />
        <input type="submit" value="Upload" className="btn" onClick={this.handleClickUpload}/>

Может кто-нибудь сообщить мне, что я делаю неправильно или что-то пропало?

1 Ответ

0 голосов
/ 14 сентября 2018

Прежде всего, посмотрите на https://s3browser.com/features-content-mime-types-editor.aspx после того, как вы сможете выяснить, какой тип вы должны использовать (для ContentType).Я думаю, что это должно быть «text / plain» или «text / html».Затем вам нужно добавить еще одно свойство к параметрам s3 с именем Body (тело должно содержать вашу сущность, которую вы хотите загрузить в корзину s3)

Вот фрагмент кода, который вы можете использоватьзагрузить свою сущность на s3 и затем получить местоположение:

let s3 = new AWS.S3({ region: process.env.AWS_REGION, apiVersion: '2006-03-01' });
let params = 
{
    Bucket:  // a bucket's location,
    Key: fileName // a path,
    Body:  // your entity to upload,
    ACL: 'public-read',
    ContentType: 'text/plain'
};

let s3Response = await s3.upload(params).promise();

      
console.log(`Entity uploaded to S3 at ${s3Response.Bucket} bucket. Location: ${s3Response.Location}`);

return s3Response.Location; 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...