обслуживание изображений с использованием nodejs и express - PullRequest
0 голосов
/ 13 января 2019

Я новичок в nodejs и выражаю. Я хочу загрузить мои изображения в каталог, скажем, my-nodejs-instances в моем текущем приложении Google, скажем, 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 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...