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

标签 javascript node.js express

我使用下面的代码从文件系统中读取get文件 该代码来自名为 Building a File Uploader with NodeJs 的博客文章.

当我运行我的项目时,我能够看到 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);

});

My question is how should I get the file from the UI with the code above? I need to get the file content from the form when I choose my file.

应用程序被部署到云端,当我使用localhost时,我使用以下代码(有效)

const readStream = fs.createReadStream("./file.html");

...

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

...

readStream.pipe(writeStream);

它从具有正确路径的文件系统创建一个文件并用另一个文件覆盖它(如这里的 index.html)。

最佳答案

正如@aedneo 所说,当用户选择文件时,文件会在上传文件夹中创建,我只需要重命名它并为写入流方法提供正确的路径即可!

关于javascript - 从表单上传文件中读取文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46478552/

相关文章:

javascript - 如果文本框值等于单选按钮值,单选按钮将激活

javascript - Cypress.io 中的 cy.readFile 和 cy.fixture 有什么区别?

javascript - 如何模拟图像按钮点击

javascript - res.redirect 没有重定向到任何地方

javascript - 实时通知 node.js

javascript - 如何在 PHP 中将 JSON 解析为 HTML 菜单

node.js - Node.js 中的 Hashmap 模块?

node.js - Express/NodeJS + Mongoose App 服务器响应慢

javascript - 尽管映射正确,Node/Express Rest API 仍不断输入相同的 Controller 功能

javascript - 将缓冲区数据转换为图像