您如何正确使用express-fileupload [英] How do you use express-fileupload correctly

查看:55
本文介绍了您如何正确使用express-fileupload的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试集成 express-fileupload 以将其上传并镜像到我的服务器.我已遵循此链接中提供的示例, express-fileupload示例,但不起作用.下面,我仅列出了与相关代码行有关的每个文件.

I'm trying to integrate express-fileupload to upload and image to my server. I have followed the example provided in this link, express-fileupload Examples but It doesn't work. Below I have included each file involved with only the relevant lines of code.

index.ejs:相关行

<form method="post" action="/images" enctype="multipart/formdata">
    <div class="panel-body form-horizontal">
        <div class="form-group col-md-12">
            <label class="col-sm-2 control-label" for="file">Browse:</label>

            <div class="col-md-10">
                <input class="form-control" type="file" name="file" id="file">
            </div>
        </div>
    </div>
</form>

server.js

const express = require('express');
const config = require('./server/configure');
let app = new express();

app.set('port', process.env.PORT || 3300);

app = config(app);

app.listen(app.get('port'), () => {
    console.log(`Server up: http://localhost:${app.get('port')}`);
});

configure.js

const express = require('express');
const path = require('path');
const expressFileUpload = require('express-fileupload');
const routes = require('./routes');

module.exports = (app) => {

    // applying expressFileUpload middleware
    app.use(expressFileUpload());

    routes(app);

    app.use('/public/', express.static(path.join(__dirname, '../public')));
    return app;
};

routes.js

const image = require('../controllers/image');

module.exports = (app) => {
    app.post('/images', image.create);
};

image.js

module.exports = {

    create(req, res) {
        let image = req.files.file;
    }
}

错误

我在下一行出现错误 let image = req.files.file; ,其中

I get an error at the following line let image = req.files.file; which states,

TypeError:无法读取未定义的属性文件"

TypeError: Cannot read property 'file' of undefined

为什么文件未定义,如何使用express-fileunload正确上传图像?

Why is file undefined and how do I correctly upload an image using express-fileunload?

推荐答案

在处理文件上传和表达时,建议您使用

When working with file upload and express I suggest you to use Multer.

文件上传非常棘手.

当一个或多个文件到达"时,到服务器,您可以使用两种不同的方法来存储它们:

When one or more files "arrive" to the Server you can store them with two different methods:

  1. 将文件保存到磁盘上已知且安全的位置
  2. 将文件保存在RAM存储器中

这两种方法各有利弊.由您决定哪个更适合您的需求.

Both methods have pro and cons. Is up to you to decide which is better for your needs.

这是我服务器中处理用户个人资料图片上传的示例(GitHub项目链接:在这里).它是用打字稿写的,但语法几乎相同.

Here is an example from my server that handle the upload of an user profile image (GitHub project link: HERE). It's written in typescript but the syntax is almost the same.

文件中间件-FileMiddleware.ts

用于处理磁盘和内存存储的中间件.我可以选择最适合特定快递路线的路线(例如中间件下的路线).

import path from 'path';
import multer from 'multer';

export default class FileMiddleware {
  public static readonly memoryLoader = multer({
    storage: multer.memoryStorage(),
    limits: {
      fileSize: 2097152, // 2 MByte
    },
  });

  public static readonly diskLoader = multer({
    storage: multer.diskStorage({
      destination: (_req, _file, cb) => {
        cb(null, path.join(__dirname, '../tmp/upload'));
      },
    }),
    limits: {
      fileSize: 67108864, // 64 MByte
    },
  });
}

用户路线-user.ts

用于处理头像文件上传的用户路径.您可以看到我正在定义路径,文件中间件(在这种情况下为内存存储-由图像密钥标识的单个文件)和用于处理该进程的控制器.

import { Router } from 'express';
import { UserController } from '@app/controller';
import { FileMiddleware } from '@app/middleware';

const router = Router();

router.post(
  '/user/avatar',
  FileMiddleware.memoryLoader.single('image'),
  UserController.updateAvatar
);

export default router;

在控制器中,您可以使用 req.file 检索图像,如此简单.

In the controller you can retrieve the image using req.file, simple as that.

正如我所说的使用Multer一样,配置和使用非常简单直观.

As I said use Multer, the configuration and use is very simple and intuitive.

PS:请记住,将文件上传与表单一起使用意味着要添加 enctype =" multipart/form-data" .

PS: Remember, using file upload with form implies adding enctype="multipart/form-data".

这篇关于您如何正确使用express-fileupload的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆