从表单上传文件中读取文件内容

3

我使用如下代码从文件系统中读取文件。这段代码来自一篇名为 使用Node.js构建文件上传器 的博客文章。

当我运行我的项目时,能够看到UI等内容。

由于我的项目中没有uploads文件夹(form.uploadDir),因此我无法使用以下代码:

app.post('/upload', function(req, res){

    // create an incoming form object
    var form = new formidable.IncomingForm();

    // specify that we want to allow the user to upload multiple files in a single request
    form.multiples = true;

    // store all uploads in the /uploads directory - cannot use it
    //form.uploadDir = path.join(__dirname, '/uploads');

    // every time a file has been uploaded successfully,
    // rename it to it's original name
    form.on('file', function(field, file) {
        fs.rename(file.path, path.join(form.uploadDir, file.name));
    });

    // log any errors that occur
    form.on('error', function(err) {
        console.log('An error has occurred: \n' + err);
    });

    // once all the files have been uploaded, send a response to the client
    form.on('end', function() {
        res.end('success');
    });
    // parse the incoming request containing the form data
    form.parse(req);

});

我的问题是如何使用上面的代码从UI获取文件?当我选择我的文件时,需要从表单中获取文件内容。
该应用程序已部署到云端,当我使用localhost时,我使用以下代码(有效)。
const readStream = fs.createReadStream("./file.html");

...

const writeStream = sftp.createWriteStream("/index.html");

...

readStream.pipe(writeStream);

这会在文件系统中创建一个具有正确路径的文件,并用另一个文件(例如此处的 index.html)覆盖它。


form.on('file'... 的回调函数中,文件不是第二个参数吗? - adeneo
@adeneo - 这就是我想的,但E2E不起作用...(我将应用程序部署到云中,因此很难调试...)有没有一些简单的方法可以将上传的文件(从form.on('file'...)打印到控制台(日志正在工作...),以便我能够看到在云中读取了表单中选择的文件内容...因此这有点棘手... - user6124024
其实所谓的“云”就是很多别人的电脑连接在一起而已。如果要记录文件,事件处理程序内部使用 console.log(file) 是一个常见的方式。 - adeneo
@adeneo - 我使用了你的建议,像这样:console.log("the file is-> " + file);,但是在控制台中我得到了 OUT the file is-> [object Object] 的输出。如果我应该写成 readStream.pipe(file); 的形式吗?请将其作为答案编写,我会关闭问题。谢谢! - user6124024
@adeneo - 请将您的建议添加为答案,以便我可以关闭并解决此问题。谢谢。 - user6124024
我不知道你是如何解决这个问题的?请发布你自己的答案并接受它。 - adeneo
1个回答

0
正如@aedneo所说,当用户选择文件时,文件会被创建在上传文件夹中,我只需要将其重命名并为写入流方法提供正确的路径,就可以使其正常工作!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接