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

查看:14
本文介绍了在 NodeJs 中使用 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.

请指教.

推荐答案

工作中我得到了一个使用 multer 模块的解决方案.使用此模块您可以上传文件和图像.并且它成功上传到目标文件夹.

Working on sometime I got a solution using multer module.Using this module you can upload both files and images.And it successfully uploaded to the destination folder.

这是我的服务器代码 app.js

var express =r equire('express');
var multer = require('multer');
var path = require('path')
var app = express();
var ejs = require('ejs')
app.set('view engine', 'ejs')
var storage = multer.diskStorage({
    destination: function(req, file, callback) {
        callback(null, './public/uploads')//here you can place your destination path
    },
    filename: function(req, file, callback) {
        callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }
})

app.get('/api/file',function(req,res){
res.render('index');
});
app.post('/api/file', function(req, res) {
    var upload = multer({
        storage: storage}).single('userFile');
    upload(req, res, function(err) {
        console.log("File uploaded");
        res.end('File is uploaded')
    })
})

app.listen(3000,function(){
console.log("working on port 3000");
});

创建一个 views 文件夹并将这个 index.ejs 文件放入其中

Create a views folder and place this index.ejs file in it

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form id="uploadForm" enctype="multipart/form-data" method="post">
        <input type="file" name="userFile" />
        <input type="submit" value="Upload File" name="submit">
    </form>
</body>
</html>

在此之后以 node app.js 运行服务器.打开浏览器并在运行此 url 后键入 http://localhost:3000/api/file 选择一个您要上传到目标文件夹的文件.并且在终端和浏览器中都有成功的响应.希望这对您有所帮助.

After this run the server as node app.js.Open the browser and type http://localhost:3000/api/file after runnig this url choose a file which you want to upload to destination folder.And have a successfull response in both terminal and browser.Hope this helps for you.

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

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