如何在node.js中使用强大的快捷方式来更改上传路径 [英] How to change upload path when use formidable with express in node.js

查看:143
本文介绍了如何在node.js中使用强大的快捷方式来更改上传路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上我遇到了两个问题。

Actually I come across two problem

首先,如何更改上传路径

我的文件夹结构如下:

|__app.js
|__upload

我的节点代码位于app.js并从中启动,
所以我要上传图片上传到上传文件夹,我更改路径:

my node code is in app.js and boot from it, so I want to the upload image upload to the upload folder, I change the path:

var form = new formidable.IncomingForm;
form.uploadDir = "./upload";

似乎上传成功,但我不知道文件在哪里,
它不在上传文件夹中。

It seems it upload successed, but I don't know where the file go, it doesn't in the upload folder.

那么正确的路径名称?

第二个问题是

如果我不更改它,它可以正确地上传到 C:/ Users / ADMINI〜1 / AppData / Local / Temp
,但是如果没有foramt,那么它将被重命名,

If I don't change it, it could upload correctly to the C:/Users/ADMINI~1/AppData/Local/Temp but it will be renamed without the foramt,

所以如何获取上传格式我自己更名为

so how can I get the upload format and renamed by myself?

第三个问题是

进程事件,
喜欢

I also bind handler to the process event, like

form.on('progress', function(bytesReceived, bytesExpected) {
    console.log(bytesReceived + ' ' + bytesExpected);
});

但似乎无法正常上传日志。为什么?我是否缺少某些东西?

but it seems doesn't work,when upload log nothing. why?Do I missing something?

这是我的所有代码:

app.post('/upload', function (req, res) {
    var form = new formidable.IncomingForm;
    // form.uploadDir = "./upload";
    console.log(form.uploadDir);

    form.parse(req, function(err, fields, files){
      if (err) return res.end('You found error');
      console.log(files.image);
    });

    form.on('progress', function(bytesReceived, bytesExpected) {
        console.log(bytesReceived + ' ' + bytesExpected);
    });

    form.on('error', function(err) {
        res.writeHead(200, {'content-type': 'text/plain'});
        res.end('error:\n\n'+util.inspect(err));
    });

    // res.end('Done');
    res.send("well done");

    return;
})


推荐答案

首先你必须您的应用程序,您不希望 bodyParser 来处理文件上传。

First of all you have to tell your app that you don't want the bodyParser to handle file uploads.

app.use(express.bodyParser());

等效的

app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart());

自己删除最后一行处理文件上传。在初始化表单时添加一些自定义选项

Remove the last line to deal with file uploads yourself. Add some custom options when initializing your form

var form = new formidable.IncomingForm({ 
  uploadDir: __dirname + '/tmp',  // don't forget the __dirname here
  keepExtensions: true
});

现在你的代码应该可以工作。

Now your code should work.

这篇关于如何在node.js中使用强大的快捷方式来更改上传路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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