Question
Image upload from Vue/Express to Spaces
I’m trying to upload a file from Vue/Express app to my DigitalOcean space, but I am having issues.
I worked through this tutorial, but in this example they are just using Express and I can’t submit the form data the way it is done in this tutorial.
https://www.digitalocean.com/community/tutorials/how-to-upload-a-file-to-object-storage-with-node-js
So, I continued playing around with it.
Here is the Vue part:
<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>
code
And in express I have my route:
const Uploads = require("./controllers/Uploads");
module.exports = app => {
app.post("/upload", Uploads.index);
};
code
And within the controller I have:
// 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");
});
}
};
code
When I upload the image I actually get the “File uploaded successfully” message, but there is no file in my bucket when I check DigitalOcean
Any help is appreciated!
These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.
×