forked from DanielOttodev/GoogleStorage-UploadTutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
61 lines (57 loc) · 1.77 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const express = require("express");
const app = express();
const port = 8080;
const path = require("path");
const { Storage } = require("@google-cloud/storage");
const Multer = require("multer");
const src = path.join(__dirname, "views");
app.use(express.static(src));
const multer = Multer({
storage: Multer.memoryStorage(),
limits: {
fileSize: 5 * 1024 * 1024, // No larger than 5mb, change as you need
},
});
let projectId = "YOUR-PROJECTID"; // Get this from Google Cloud
let keyFilename = "PATH-TO-YOUR-KEYFILE.json"; // Get this from Google Cloud -> Credentials -> Service Accounts
const storage = new Storage({
projectId,
keyFilename,
});
const bucket = storage.bucket("YOUR-STORAGE-BUCKET"); // Get this from Google Cloud -> Storage
// Gets all files in the defined bucket
app.get("/upload", async (req, res) => {
try {
const [files] = await bucket.getFiles();
res.send([files]);
console.log("Success");
} catch (error) {
res.send("Error:" + error);
}
});
// Streams file upload to Google Storage
app.post("/upload", multer.single("imgfile"), (req, res) => {
console.log("Made it /upload");
try {
if (req.file) {
console.log("File found, trying to upload...");
const blob = bucket.file(req.file.originalname);
const blobStream = blob.createWriteStream();
blobStream.on("finish", () => {
res.status(200).send("Success");
console.log("Success");
});
blobStream.end(req.file.buffer);
} else throw "error with img";
} catch (error) {
res.status(500).send(error);
}
});
// Get the main index html file
app.get("/", (req, res) => {
res.sendFile(src + "/index.html");
});
// Start the server on port 8080 or as defined
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});