Multer 不创建文件

发布于 2025-01-19 19:38:08 字数 3812 浏览 2 评论 0原文

我在使用 multer 创建文件时遇到问题。

文件架构:

My app folder
   Back
      config
        -config.json
      images
      middleware
        -auth.js
        -multer-config.js
      migrations
        -create-user.js
        -create-message.js
      models
        -index.js
        -message.js
        -user.js
      node_modules
      routes
        -posts.js
        -users.js
      -.env
      -app.js
      -server.js
      -package.json
      -package-lock.json

   Front
      --some files

前面:

async handleSubmit() {

    var formData = new FormData();
    formData.append('image', this.file[0]);

    await fetch("http://localhost:3000/api/sendTest",{
    method: 'POST',
    body: formData,
    headers:{"content-type": "multipart/form-data; boundary=image", "authorization": this.$store.state.jwt}
    });

}

后面(/back/routes/posts.js):

const express = require('express');
const router = express.Router();
var models = require('../models');
const auth = require('../middleware/auth');
const multer = require('../middleware/multer-config');

router.post('/sendTest', auth, multer, async (req, res, next) => {
    try {

        console.log(req.file); // return undefined

        res.status(201).json({
            message: 'Message publié'
        });

    } catch (err) {
        res.status(400).json({ message: err.original.sqlMessage });
    }

});

后面(/back/app.js):multer-config:console.log(this.file[0

const express = require('express');
const app = express();
const helmet = require('helmet'); 
const path = require('path');
app.use(helmet()); 

// Routage
const postsRoutes = require("./routes/posts");
const usersRoutes = require("./routes/users");

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*'); 
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization'); 
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
    next();
});

app.use(express.json());

app.use('/api', express.static(path.join(__dirname, 'images')));
app.use('/api', postsRoutes);
app.use('/api', usersRoutes);

module.exports = app;

]

const multer = require('multer');

const MIME_TYPES = {
  'image/jpg': 'jpg',
  'image/jpeg': 'jpg',
  'image/png': 'png',
  'image/gif': 'gif'
};

const storage = multer.diskStorage({
  destination: (req, file, callback) => {
    callback(null, 'images');
  },
  filename: (req, file, callback) => {
    const name = file.originalname.split(' ').join('_');
    const extension = MIME_TYPES[file.mimetype];
    callback(null, name + Date.now() + '.' + extension);
  }
});

module.exports = multer({storage: storage}).single('images');

)从前面返回:

File { name: "Screenshot_2.jpg", lastModified: 1635463756273, webkitRelativePath: "", size: 117741, type: "image/jpeg" }

console.log( formData) 从前面返回:

FormData {  }

但是,这是正常的,我们必须使用键:

for (var [key, value] of formData.entries()) { 
  console.log(key, value);
}

returns

image 
File { name: "Screenshot_2.jpg", lastModified: 1635463756273, webkitRelativePath: "", size: 117741, type: "image/jpeg" }

我们可以在中看到请求Network

因此,我认为 Front 发送的文件格式很好。

据我了解,multer 必须在“/back/images”中创建文件,然后我们应该能够在路由“/sendTest”中使用 req.file,但它返回未定义。

我正在使用sequelize 连接到数据库。

我不确定是否在“auth”之后调用 multer,因为当我发送请求时,multer-config 中的 console.log(“test”) 应该显示在控制台“test”中,控制台中什么也没有出现,除非我更改后保存“multer-config”文件。

如果有人知道如何解决问题或在某个地方看到错误,我很感兴趣!

I have a problem with file creation with multer.

File architecture:

My app folder
   Back
      config
        -config.json
      images
      middleware
        -auth.js
        -multer-config.js
      migrations
        -create-user.js
        -create-message.js
      models
        -index.js
        -message.js
        -user.js
      node_modules
      routes
        -posts.js
        -users.js
      -.env
      -app.js
      -server.js
      -package.json
      -package-lock.json

   Front
      --some files

Front:

async handleSubmit() {

    var formData = new FormData();
    formData.append('image', this.file[0]);

    await fetch("http://localhost:3000/api/sendTest",{
    method: 'POST',
    body: formData,
    headers:{"content-type": "multipart/form-data; boundary=image", "authorization": this.$store.state.jwt}
    });

}

Back (/back/routes/posts.js):

const express = require('express');
const router = express.Router();
var models = require('../models');
const auth = require('../middleware/auth');
const multer = require('../middleware/multer-config');

router.post('/sendTest', auth, multer, async (req, res, next) => {
    try {

        console.log(req.file); // return undefined

        res.status(201).json({
            message: 'Message publié'
        });

    } catch (err) {
        res.status(400).json({ message: err.original.sqlMessage });
    }

});

Back (/back/app.js):

const express = require('express');
const app = express();
const helmet = require('helmet'); 
const path = require('path');
app.use(helmet()); 

// Routage
const postsRoutes = require("./routes/posts");
const usersRoutes = require("./routes/users");

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*'); 
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content, Accept, Content-Type, Authorization'); 
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
    next();
});

app.use(express.json());

app.use('/api', express.static(path.join(__dirname, 'images')));
app.use('/api', postsRoutes);
app.use('/api', usersRoutes);

module.exports = app;

multer-config:

const multer = require('multer');

const MIME_TYPES = {
  'image/jpg': 'jpg',
  'image/jpeg': 'jpg',
  'image/png': 'png',
  'image/gif': 'gif'
};

const storage = multer.diskStorage({
  destination: (req, file, callback) => {
    callback(null, 'images');
  },
  filename: (req, file, callback) => {
    const name = file.originalname.split(' ').join('_');
    const extension = MIME_TYPES[file.mimetype];
    callback(null, name + Date.now() + '.' + extension);
  }
});

module.exports = multer({storage: storage}).single('images');

console.log(this.file[0]) from front returns :

File { name: "Screenshot_2.jpg", lastModified: 1635463756273, webkitRelativePath: "", size: 117741, type: "image/jpeg" }

console.log(formData) from front returns :

FormData {  }

But, that's normal, we have to use keys:

for (var [key, value] of formData.entries()) { 
  console.log(key, value);
}

returns

image 
File { name: "Screenshot_2.jpg", lastModified: 1635463756273, webkitRelativePath: "", size: 117741, type: "image/jpeg" }

We can see the request in Network

I think the file format sent from Front is therefore good.

As i understand multer has to create the file in "/back/images" and then we should be able to use req.file in the route "/sendTest" but it returns undefined.

I'm using sequelize to connect to database.

I'm not sure if multer is called after "auth" because a console.log("test") in multer-config should display in the console "test" when I send my request, nothing appears in the console, except when I save the "multer-config" file after a change.

If anyone has an idea of how to fix the problem or sees an error somewhere, I'm interested!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

熟人话多 2025-01-26 19:38:08

我发现错误:

返回(/back/app.js):
替换

app.use('/api', express.static(path.join(__dirname, 'images')));

app.use('/images', express.static(path.join(__dirname, 'images')));

前面:
删除标题内容类型:

    await fetch("http://localhost:3000/api/sendTest",{
    method: 'POST',
    body: formData,
    headers:{"authorization": this.$store.state.jwt}
    });

然后现在文件已上传!

希望它对你有用:)

I found errors:

Back (/back/app.js):
replace

app.use('/api', express.static(path.join(__dirname, 'images')));

by

app.use('/images', express.static(path.join(__dirname, 'images')));

Front:
Remove headers content-type:

    await fetch("http://localhost:3000/api/sendTest",{
    method: 'POST',
    body: formData,
    headers:{"authorization": this.$store.state.jwt}
    });

Then now files are uploaded !

Hope it be useful for you :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文