简体   繁体   中英

Cannot read property 'file' of undefined in express when trying to upload image

I learn Express.

I got error when trying to upload image using exprees.

the error is Cannot read property 'file' of undefined.

Here my codes, hope that anyone could helpme..

user.service.js

create: (fileRequest, data, callBack) => {
      pool.query(
        `insert into registration(email, password, first_name, last_name, education, university, language, file_gambar) 
                  values(?,?,?,?,?,?,?,?)`,
        [
          data.email,
          data.password,
          data.first_name,
          data.last_name,
          data.education,
          data.university,
          data.language,
          fileRequest.name
        ],
        (error, results, fields) => {
          if (error) {
            callBack(error);
          }
          return callBack(null, results);
        }
      );
    },

user.controller.js

createUser: (req, res) => {
      const data = req.body;
      const salt = genSaltSync(10);
      data.password = hashSync(data.password, salt);

      const fileRequest = req.files.file;

      create(fileRequest, data, (err, results) => {
        if (req.files){
          fileRequest.mv("./file_store" + fileRequest.name, (error) => {
            if (error){
              throw error;
            } else {
              if (err) {
                console.log(err);
                return res.status(500).json({
                  success: 0,
                  message: "Database connection error"
                });
              }
              return res.status(200).json({
                success: 1,
                data: results
              });
            }
          })
        }
      });
    },

app.js

require("dotenv").config();
const express = require("express");
const app = express();
const connection = require('cors');
const upload = require('express-fileupload');
const userRouter = require("./api/users/user.router");
const projectRouter = require("./api/projects/project.router");
const detailRouter = require("./api/details/detail.router");

app.use(express.json());
app.use(connection());
app.use(upload());

app.use("/users", userRouter);
app.use("/projects", projectRouter);
app.use("/details", detailRouter);

app.listen(process.env.APP_PORT, ()=>{
    console.log("Server up and running on PORT: ", process.env.APP_PORT);
});

what is wrong with my codes and what should I do? thank for the help before :)

上传文件/文档/图片时,密钥的名称应为“文件”,并确保该值是您正在上传的实际文件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM