【问题标题】:NodeJS having trouble with file uploads in TypeScript projectNodeJS 在 TypeScript 项目中无法上传文件
【发布时间】:2014-03-31 03:33:51
【问题描述】:

我正在尝试使用强大的模块将文件上传到 NodeJS 服务器。上传后,我想将文件重命名为其他名称,为此我需要获取上传文件的名称和路径。根据 formidable 提供的文档,您必须调用 Formidable.File 类来获取正在写入文件的文件路径。

这是文档: https://github.com/felixge/node-formidable#formidableincomingform

我的项目是用 Typescript 编写的,所以我为 Formidable 编写了一个 Typescript 定义,其中仅包含我需要调用的那些文字。这在另一个文件 Upload.ts 中调用

这是 formidable 的 typescript 定义

declare module "formidable" {

    export class IncomingForm{
        uploadDir: String;
        keepExtensions: Boolean;
        type: String;
        parse(req, Function) : void;
    }

    export class File{
        name: String;
        path: String;
    }

}

上传.ts

public upload(req, res){
        var form  = new formidable.IncomingForm();
        var file = new formidable.File();
        var originalFileName = file.name;
        form.uploadDir = this.directory;
        form.keepExtensions  = true;
        form.type = 'multipart';
        form.parse(req, function(err, fields, files) {
            res.writeHead(200, {'content-type': 'text/plain'});
            res.write('received upload:\n\n');
            res.end(util.inspect({fields: fields, files: files}));
        });
        return;
    }

当我点击“上传”按钮时,它会导致错误提示:

var file = new formidable.File();
TypeError: undefined is not a function

根据文档,我的定义似乎是正确的,但我不明白这个错误。

【问题讨论】:

    标签: node.js typescript


    【解决方案1】:

    您无法通过创建新的空File 实例来获取上传文件的路径。

    parse 方法回调中的files 参数包含上传文件的File 对象。

    【讨论】:

    • 谢谢。这解决了问题。我也想知道你能不能告诉我“err”和“fields”对象是从哪里来的,它们的类型是什么。
    • @EternallyCurious:我在文档中找不到它,所以 err 参数应该是一个 Error 对象:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…fields 参数应该是一个集合从表单中不是文件上传字段的字段填充的键值对,其结构与通常在 node.js 中处理的 POST 数据相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    • 2021-07-31
    • 2015-09-09
    • 1970-01-01
    • 2016-12-13
    • 2021-05-14
    相关资源
    最近更新 更多