将影像从Vue / Express上传到DigitalOcean空间

时间:2018-07-03 17:26:25

标签: express amazon-s3 vue.js multer multer-s3

我正在尝试将文件从Vue / Express应用程序上传到我的DigitalOcean空间,但是遇到问题。

我已经完成了本教程的学习,但是在本示例中,他们只是使用Express,而我无法按照本教程中的方式提交表单数据。 https://www.digitalocean.com/community/tutorials/how-to-upload-a-file-to-object-storage-with-node-js

所以,我继续玩弄它。

这是Vue的一部分:

<template>
  <div>
    <h1>Upload a file</h1>

    <label>File
        <input type="file" id="file" ref="file" name="file" v-on:change="handleFileUpload()"/>
      </label>
        <button v-on:click="submitFile()">Submit</button>
</div>

</template>


<script>
import axios from "axios";
export default {
  data() {
    return {
      file: ""
    };
  },

  methods: {
    submitFile() {
      // Initialize the form data
      let formData = new FormData();
      // Add the form data we need to submit
      formData.append("file", this.file);
      // Make the request to the POST /single-file URL
      axios
        .post("/upload", file, {
          baseURL: "http://localhost:8000/"
          // headers: {
          //   "Content-Type": "multipart/form-data"
          // }
        })
        .then(function() {
          console.log("SUCCESS!!");
        })
        .catch(function() {
          console.log("FAILURE!!");
        });
    },
    // Handles a change on the file upload
    handleFileUpload() {
      this.file = this.$refs.file.files[0];
    }
  }
};
</script>

很明显,我有我的路线:

const Uploads = require("./controllers/Uploads");

module.exports = app => {
  app.post("/upload", Uploads.index);
};

在控制器中,我有:

// Load dependencies for file uploading to DO
const aws = require("aws-sdk");
const multer = require("multer");
const multerS3 = require("multer-s3");

// Set S3 endpoint to DigitalOcean Spaces
const spacesEndpoint = new aws.Endpoint("nyc3.digitaloceanspaces.com");
const s3 = new aws.S3({
  endpoint: spacesEndpoint
});

// Image upload middleware
// Change bucket property to your Space name
const upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: "1410",
    acl: "public-read",
    key: function(request, file, cb) {
      console.log(file);
      cb(null, file.originalname);
    }
  })
}).array("upload", 1);

module.exports = {
  index(req, res) {
    console.log("backend hit");
    upload(req, res, function(error) {
      if (error) {
        console.log(error);
        return res.redirect("/error");
      }
      console.log("File uploaded successfully.");
      res.redirect("/success");
    });
  }
};

上传图像时,我实际上收到了“文件上传成功”消息,但是当我检查DigitalOcean时,存储桶中没有文件

感谢您的帮助!

0 个答案:

没有答案