用强大的文件名解析表单值 [英] Parse form value with formidable to filename

查看:81
本文介绍了用强大的文件名解析表单值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用强大的功能来处理我在NodeJ中上传的文件.我有点无法解析字段值.

I´m using formidable to handle my file uploads in NodeJs. I´m a little stuck at parsing field values.

如何将project_id的值获取到表单处理程序,以便可以在文件名中写入参数?

How do I get the value of project_id to the form handler, so I can write the parameter in my filename?

<input type="text" id="project_id" value="{{projects._id}}" readonly>

编辑

更具体地说,这是我的表单上载处理的详细视图:

To be more specific, here´s a detailed view of my form-upload handling:

app.post('/uploads/', function (req, res){
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        res.writeHead(200, {'content-type': 'image/jpeg'});
        res.write('received upload: \n\n');
        var project = fields.project_id;
        res.end(util.inspect(project, {fields: fields, files: files}));
    });

    form.on('end', function(project, fields, files){ 
        console.log(project); 
        /*Temporary location of our uploaded file */
        var temp_path = this.openedFiles[0].path;
        /*The file name of the uploaded file */
        var file_name =  project + '.' + this.openedFiles[0].name;

我可以在form.parse部分中记录var project.但是我没有在form.on('end'...部分得到变量.

I can log the var project in the form.parse part. But I don´t get the variable in the form.on('end'... part.

HTML表单

<form   id="uploadForm"
    enctype="multipart/form-data"
    action="/uploads/"
    method="post">
    <input type="text" name="project_id" id="project_id" value="{{projects._id}}" readonly>
    <input multiple="multiple" type="file" name="upload" />
    <button type="submit">Upload</button>
</form>

推荐答案

Formidable的end回调不接受任何参数,但是如果使用parse,我不确定您是否甚至需要调用它打回来.我认为您正在寻找的是这样的:

Formidable's end callback doesn't take any parameters, but I'm not sure you even need to call it if you're using the parse callback. I think what you're looking for is something like this:

var fs = require('fs');
app.post('/uploads', function(req, res, next) {
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
        if (err) next(err);

        // TODO: make sure my_file and project_id exist    
        fs.rename(files.my_file.path, fields.project_id, function(err) {
            if (err) next(err);
            res.end();
        });
    });
});

如果您选择不使用parse回调,则需要侦听end()事件,如下所示:

You would need to listen for the end() event if you chose not to use the parse callback, like this:

new formidable.IncomingForm().parse(req)
    .on('file', function(name, file) {
        console.log('Got file:', name);
    })
    .on('field', function(name, field) {
        console.log('Got a field:', name);
    })
    .on('error', function(err) {
        next(err);
    })
    .on('end', function() {
        res.end();
    });

这篇关于用强大的文件名解析表单值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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