ENOENT: no such file or directory .?

2020-02-28 04:29发布

This is error which am getting while post data and file. I have followed 'academind' tutorial for building Restful API services, also i have been searching answer for this type of errors but nothing works for me.

Am using "multer" to upload file

The folder 'uploads' available in the folder but it shows

ENOENT: no such file or directory, open 'D:\project\uploads\2018-01-24T07:41:21.832Zcheck.jpg'"

app.js

const express = require("express");
const app = express();
const morgan = require("morgan");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const productRoutes = require("./api/routes/products");

mongoose.connect('',
(err)=>{
    if(err){console.log(err)}
    else{console.log('DB Connected')}
})
mongoose.Promise = global.Promise;

app.use(morgan("dev"));
app.use('/uploads', express.static('uploads'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  );
  if (req.method === "OPTIONS") {
    res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
    return res.status(200).json({});
  }
  next();
});

// Routes which should handle requests
app.use("/products", productRoutes);

app.use((req, res, next) => {
  const error = new Error("Not found");
  error.status = 404;
  next(error);
});

app.use((error, req, res, next) => {
  res.status(error.status || 500);
  res.json({
    error: {
      message: error.message
    }
  });
});

module.exports = app;

product.js

const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const multer = require('multer');

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, './uploads/');
  },
  filename: function(req, file, cb) {
    cb(null, new Date().toISOString() + file.originalname);
  }
});

const fileFilter = (req, file, cb) => {
  // reject a file
  if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 5
  },
  fileFilter: fileFilter
});

router.post("/", checkAuth, upload.single('productImage'), (req, res, next) => {
  const product = new Product({
    _id: new mongoose.Types.ObjectId(),
    name: req.body.name,
    price: req.body.price,
    productImage: req.file.path 
  });
  product
    .save()
    .then(result => {
      console.log(result);
      res.status(201).json({
        message: "Created product successfully",
        createdProduct: {
            name: result.name,
            price: result.price,
            _id: result._id,
            request: {
                type: 'GET',
                url: "http://localhost:3000/products/" + result._id
            }
        }
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
        error: err
      });
    });
});

module.exports = router;

8条回答
【Aperson】
2楼-- · 2020-02-28 04:41

You don't have permission to access /uploads/ on this server.

Try the following:

sudo chmod -R 777 /uploads
查看更多
够拽才男人
3楼-- · 2020-02-28 04:42

in product.js

new Date().toISOString() Behind add replace() change ":"

Windows OS file don't accept ":" named

on youtube is the MAC OS

E.g

new Date().toISOString().replace(/:/g, '-')

查看更多
聊天终结者
4楼-- · 2020-02-28 04:43

change destination and create uploads folder

 destination: function (req, file, cb) {
    cb(null, path.join(__dirname, '../uploads/'))
  },
查看更多
Deceive 欺骗
5楼-- · 2020-02-28 04:50

Try the following:

  1. Require this as a constant (const path = require('path');)
  2. Change this line

    cb(null, './uploads/');

With this:

cb(null, path.join(__dirname, '/uploads/'));

As I can see, you are trying to get a path that is not on served on the server, but rather a path that is on the server machine.

UPDATE

Try also changing this

app.use('/uploads', express.static('uploads'));

To this:

app.use(express.static(__dirname));

In order to expose the __dirname for static files.

查看更多
再贱就再见
6楼-- · 2020-02-28 04:51

So the answer is in the tutorials comments section on youtube. Instead of:

cb(null, new Date().toISOString() + file.originalname);

do:

cb(null, Date.now() + file.originalname);

Simple as.

查看更多
对你真心纯属浪费
7楼-- · 2020-02-28 04:55

every thing is fine. problem is on this line cb(null, new Date().toISOString() + file.originalname); simply write cb(null,file.originalname); it will work. try to use in different way to add the date string with file name.

查看更多
登录 后发表回答