使用Multer重命名上传的文件不起作用

使用Multer重命名上传的文件不起作用

本文介绍了使用Multer重命名上传的文件不起作用(Express.js)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Express.js和Multer从HTML表单上载文件.我设法将文件保存到所需的位置(名为 uploads 的文件夹).

I'm trying to upload a file from a HTML form using Express.js and Multer. I've managed to save the file to the desired location (a folder named uploads).

但是,我想在上传文件时重命名文件,因为默认情况下,Multer给它起了一个奇怪的名字,例如:

However, I'd like to rename the file while uploading it because, by default, Multer gives it a strange name such as:

可能是十六进制的时间戳,但是我需要一个更明确的名称,以便以后在其上调用脚本.

Might be a hexadecimal time stamp or so but I need a more explicit name in order to call a script on it later.

我已按照此处找到的说明进行操作,但它没有做任何比以往更多的事情:上传具有六名的文件.

I've followed the explanation found here but it doesn't do anything more than it used to: uploading the file with the hexa name.

此外,两个事件 onFileUploadStart onFileUploadComplete 似乎从未触发,因为我没有在控制台中记录任何内容.

Also, the two events onFileUploadStart and onFileUploadComplete never seem to be triggered as I don't get anything logged in my console.

我正在为服务器和路由使用两个单独的文件:

I am using two separate files for the server and the routing:

app.js

app.js

/**
 * Dependencies
 */

var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

/**
 * Importation of routes
 */
var routes = require('./routes/index');
var recog = require('./routes/recog');

/**
 * Express
 */
var app = express();

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// pour contrer les erreurs de cross domain
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

/**
 * Routes
 */
app.use('/', routes);
app.use('/recog', recog);

module.exports = app;

recog.js

recog.js

/**
 * Requirements
 */
var express = require('express');
var router = express.Router();
var multer = require('multer');
var uploads = multer({
    dest: 'uploads/',
    rename: function (fieldname, filename) {
        console.log("Rename...");
        return filename + Date.now();
    },
    onFileUploadStart: function () {
        console.log("Upload is starting...");
    },
    onFileUploadComplete: function () {
        console.log("File uploaded");
    }
});

/**
 * Upload d'une image
 */
router.post('/upload', uploads.single('image'), function (req, res, next) {
    console.log("Front-end is calling");
    res.json({status: 'success', data: 'Fichier chargé.\nOrgane sélectionné : ' + req.body.organ});
});

module.exports = router;

我一直在研究,但是由于我对Node.js和JavaScript相当陌生,所以我无法弄清楚问题出在哪里.

I have been digging around but I can't figure out what the problem is as I am quite new to Node.js and JavaScript in general.

感谢您的帮助!

推荐答案

Multer的用法已更改.

The usage for Multer has changed.

当前Multer构造函数仅接受三个选项:

Currently Multer constructor accepts only three options:

  1. dist/storage
  2. fileFilter
  3. 限制

现在重命名,onFileUploadStart,onFileUploadComplete将不起作用.

now rename, onFileUploadStart, onFileUploadComplete would not work.

但是可以使用DiskStorage重命名

however renaming can be done using DiskStorage

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, '/tmp/my-uploads')
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now())
  }
})

var upload = multer({ storage: storage })

看看这些链接:

  • https://github.com/expressjs/multer
  • multer callbacks not working ?

这篇关于使用Multer重命名上传的文件不起作用(Express.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:37