我是nodejs和express的新手。我想将图像上传到当前Google应用程序下的目录my-nodejs-instances中,并说myapplication。我有一半的代码可以上传图片,但我不知道如何显示。是不是很复杂,或者我只是想念一两行?
const http = require("http");
const path = require("path");
const fs = require("fs");
const express = require("express");
const app = express();
app.use('/public',express.static(__dirname + '/public'));
const httpServer = http.createServer(app);
const PORT = process.env.PORT || 8080;
const multer = require("multer");
const handleError = (err, res) => {
res
.status(500)
.contentType("text/plain")
.end("Oops! Something went wrong!");
};
const upload = multer({
dest: "uploaded/"
https://github.com/expressjs/multer#limits
});
app.post(
"/upload",
upload.single("file" /* name attribute of <file> element in your form */),
(req, res) => {
const tempPath = req.file.path;
const targetPath = path.join(__dirname, "./uploads/image.jpg");
if (path.extname(req.file.originalname).toLowerCase() === ".jpg") {
fs.rename(tempPath, targetPath, err => {
if (err) return handleError(err, res);
res
.status(200)
.contentType("text/plain")
.end("File uploaded!");
});
} else {
fs.unlink(tempPath, err => {
if (err) return handleError(err, res);
res
.status(403)
.contentType("text/plain")
.end("Only .jpg files are allowed!");
});
}
}
);
app.get("/image.jpg", (req, res) => {
res.sendFile(path.join(__dirname, "./uploads/image.jpg"));
});
httpServer.listen(8080, () => {
console.log(`Server is listening on port ${PORT}`);
});
app.get("/", express.static(path.join(__dirname, "./public")));
display my image