上传图片,无需重定向快递:(

时间:2015-02-20 01:46:02

标签: javascript express formidable

有没有办法在没有重定向到/ upload路径的情况下使用强力?

在网上和文档中找到..

HTML

<form action="/upload" enctype="multipart/form-data" method="post">
   <input type="file" name="file">
   <input type="submit" value="Upload">
</form>

EXPRESS

 var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
  console.log(87987)
  console.log(files)
  console.log(files.file)
    // `file` is the name of the <input> field of type `file`
    var old_path = files.file.path,
        file_size = files.file.size,
        file_ext = files.file.name.split('.').pop(),
        index = old_path.lastIndexOf('/') + 1,
        file_name = old_path.substr(index),
        new_path = path.join(process.env.PWD, 'public/uploads/', file_name + '.' + file_ext);

    fs.readFile(old_path, function(err, data) {
        fs.writeFile(new_path, data, function(err) {
            fs.unlink(old_path, function(err) {
                if (err) {
                    res.status(500);
                    res.json({'success': false});
                } else {
                    res.status(200);
                    res.json({'success': true});
                }
            });
        });
    });
});

图片上传到文件夹,但由于表单元素中的“action ='/ upload'”属性,我被重定向到/ uploads路径。

我想留在同一页面,但当我尝试更改“操作”值时,我无法将图像发送到服务器

1 个答案:

答案 0 :(得分:0)

使用res.redirect或从表单中删除action属性以发布到当前页面。

http://expressjs.com/api.html#res.redirect

如果您删除action属性以发布到当前页面,那么您必须添加一条路线来表达该页面以处理post请求

http://expressjs.com/api.html#app.route

如果您在删除action属性时遇到问题,请尝试使用action="?"发布到当前页面。

相关问题