在NodeJ中使用Multer上传文件时出错 [英] Error uploading files using Multer in NodeJs

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

问题描述

我正在尝试编写基于Express的API来上传文件.文件名和目录路径应动态设置.

I am trying to write an Express-based API for uploading files. The filename and directory path should be set dynamically.

我的代码:

var crypto = require('crypto')
var express = require('express');
var fs = require('fs');
var mime = require('mime');
var mkdirp = require('mkdirp');
var multer = require('multer');

var app = express();
var path = './uploads'; 

var storage = multer.diskStorage({
    destination: function (req, file, callback) {
        callback(null, path);
        console.log('Im in storage destination'+path);
    },
    filename: function (req, file, callback) {
        console.log('Im in storage filename'+path);
        //callback(null, file.fieldname + '-' + Date.now());
        crypto.pseudoRandomBytes(16, function (err, raw) {
            callback(null, Date.now() + '.' + mime.extension(file.mimetype));
        });
    }
});

var upload = multer({ storage : storage}).single('userPhoto');

app.post('/photo',function(req,res){
    path += '/pics/shanmu/';
    console.log('Im in post , outside upload'+path);

    upload(req,res,function(err) {
        console.log('Im in post , inside upload'+path);
        if(err) {
            return res.end('Error uploading file.');
        }
        res.end('File is uploaded'+path);
        console.log('File is uploaded'+path);
    });
});

app.listen(3000,function(){
    console.log('Working on port 3000');
});

我的文件夹结构:

运行代码时,应将文件上传到uploads/文件夹中. (此文件夹中有两个嵌套文件夹-uploads/pics/shanmu.)

When I run the code, the file should be uploaded in the uploads/ folder. (This folder has two nested folders inside it - uploads/pics/shanmu).

当我从邮递员那里触发它时,它只能工作一次.第二次尝试时,无法上传文件.

When I triggered it from postman, it only works once. When I try the second time, I cannot upload files.

请告知.

推荐答案

我让您的代码正常工作.参见:

I got your code working. See:

https://gist.github.com/lmiller1990/3f1756efc07e09eb4f44e20fdfce30a4

我认为问题出在您声明destination的方式上.我不确定为什么.我只是通过将路径作为字符串传递来使其工作.

I think the problem was with the way you declared destination. I'm not sure why, though. I got it working by just passing the path as a string.

祝你好运!

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

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