Ax ios сообщение на AWS s3 не появляется - изображение не появляется в s3 Bucket - Nodejs, React, JavaScript, Adonisjs - PullRequest
0 голосов
/ 05 марта 2020

В настоящее время я создаю регистрационную форму с помощью React, Redux, JavaScript, Node и Adonis js. Я пытаюсь загрузить изображения профиля в мое AWS s3 Bucket. На данный момент я получил его, поэтому ответ возвращает 200 назад, но в ведре ничего не появляется. Наряду с 200 я также получаю ссылку на изображение, когда я нажимаю, мне отказывают в доступе, а также, что я не вижу его в корзине? (См. Изображение).

AWS ССЫЛКА, КОТОРАЯ ВОЗВРАЩАЕТ ИЗОБРАЖЕНИЕ

Когда я изменяю тело параметров в контроллере на имя файла, оно передается в корзину, но отображается только имя файла не фактическое изображение.

Я что-то упустил? Пожалуйста, смотрите ниже.

Контроллер:

"use strict";

require("dotenv").config();
const aws = require("aws-sdk");
const fs = require("fs");
const Helpers = use("Helpers");
const Drive = use("Drive");

class awsController {
  async upload({ request, response }) {
    aws.config.update({
      region: "ap-southeast-2", // AWS region
      accessKeyId: process.env.S3_KEY,
      secretAccessKey: process.env.S3_SECERT
    });

    // The below defines the buckets name
    const S3_BUCKET = process.env.S3_BUCKET;

    // The below creates a new s3 instance with the correct params and keys
    const s3Bucket = new aws.S3({
      region: "ap-southeast-2",
      accessKeyId: process.env.S3_KEY,
      secretAccessKey: process.env.S3_SECERT,
      Bucket: process.env.S3_BUCKET
    }); // Create a new instance of S3

    // The below collects the data from the post including filename, type and the complete file object.

    const uploadedFile = request.all().body;
    console.log(uploadedFile);
    const fileName = request.all().body.fileName;
    const fileType = request.all().body.fileType;

    // The below defines the params.
    const params = {
      Bucket: S3_BUCKET,
      Key: fileName,
      Body: uploadedFile,
      ContentType: fileType,
      ACL: "public-read"
    };

    // The below sends the object off to AWS s3
    s3Bucket.putObject(params, function(err, data) {
      if (err) {
        response.send(err);
      }
      const returnData = {
        signedRequest: data,
        url: `https://${S3_BUCKET}.s3.amazonaws.com/${fileName}`
      };

      console.log("Success");
      response.send(returnData);
    });
  }
}

module.exports = awsController;

Форма регистрации и топор ios Почтовая команда:

import React, { Component } from "react";
import axiosAPI from "./../resorterAPI";
import axios from "axios";

class ImageUpload extends Component {
  constructor(props) {
    super(props);
    this.state = {
      success: false,
      url: ""
    };
  }

  handleChange = event => {};

  handleUpload = event => {
    // The below grabs the first file.
    let uploadedFile = this.uploadInput.files[0];

    // Splits name of file
    let fileParts = uploadedFile.name.split(".");
    let fileName = fileParts[0];
    let fileType = fileParts[1];
    let fileLastModified = uploadedFile.lastModified;
    let fileSize = uploadedFile.size;
    let fullFileName = uploadedFile.name;

    console.log("Preparing upload");

    // Below makes a post request to API with all the necessary data.
    // Math round and random are used to ensure each file has a unique name.
    axiosAPI
      .post("/s3Upload", {
        header: {
          "Content-Type": "application/json"
        },
        body: {
          lastModified: fileLastModified,
          size: fileSize,
          fileName:
            Math.round(Math.random() * 1000 * 300000).toString() +
            "_" +
            fileName,
          fileType: fileType
        }
      })
      .then(response => {
        console.log(response.data);
        const returnData = response.data;
        const imageURL = response.data.url;
      });
  };

  render() {
    console.log(this.state);
    return (
      <div>
        <center>
          <input
            onChange={this.handleChange}
            ref={ref => {
              this.uploadInput = ref;
            }}
            type="file"
          />
          <br />
          <button onClick={this.handleUpload}> Upload </button>
        </center>
      </div>
    );
  }
}

export default ImageUpload;

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