使用multer with expressjs上传文件时出错 [英] Error handling when uploading file using multer with expressjs

查看:155
本文介绍了使用multer with expressjs上传文件时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 multer 将文件保存在通过快捷方式开发的服务器上。的NodeJS。

I am using multer to save the file on server developed through express & nodejs.

我正在使用以下代码。

var express = require('express'),
    multer  = require('multer')

var app = express()

app.get('/', function(req, res){
  res.send('hello world');
});

app.post('/upload',[ multer({ dest: './uploads/'}), function(req, res){

    res.status(204).end()
}]);

app.listen(3000);

Multer将文件保存在指定的目标文件夹中。

Multer saves the file for me in the specified destination folder.

所有这一切都正常,但我有以下问题:


  1. 如果由于各种原因文件保存失败,看起来我的路由总是返回状态204.

  2. 我不确定文件保存后状态204是否被取消,当文件正在异步保存时,返回状态204。


推荐答案

您可以处理错误使用 onError 选项:

You can handle errors using the onError option:

app.post('/upload',[
  multer({
    dest    : './uploads/',
    onError : function(err, next) {
      console.log('error', err);
      next(err);
    }
  }),
  function(req, res) {
    res.status(204).end();
  }
]);

如果您调用 next(err)您的路由处理程序(生成204)将被跳过,错误将由Express处理。

If you call next(err), your route handler (generating the 204) will be skipped and the error will be handled by Express.

我认为(不是100 %确定,这取决于如何实现 multer 实现)当保存文件时,将调用您的路由处理程序。您可以使用 onFileUploadComplete 在上传完成时记录消息,并将其与调用路由处理程序时进行比较。

I think (not 100% sure as it depends on how multer is implemented) that your route handler will be called when the file is saved. You can use onFileUploadComplete to log a message when the upload is done, and compare that to when your route handler is called.

查看代码, code> multer 在完全上传文件时调用下一个中间件/路由处理程序。

Looking at the code, multer calls the next middleware/route handler when the file has been uploaded completely.

这篇关于使用multer with expressjs上传文件时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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