【问题标题】:Node JS: File upload Error [ERR_STREAM_WRITE_AFTER_END]节点 JS:文件上传错误 [ERR_STREAM_WRITE_AFTER_END]
【发布时间】:2020-02-12 01:45:00
【问题描述】:

所以我想要做的是,我只是在强大模块的帮助下使用 nodeJS 将文件上传到特定文件夹,使用以下参考。 File Upload using nodeJS

现在,我的文件被上传到我想要的文件夹,但是当我从 CLI 运行命令时,它给了我一个错误

这是我尝试过的代码

var http = require('http') ;
var formidable = require('formidable') ;
var fs = require('fs');


http.createServer(function(req, res){
if(req.url == '/fileUpload'){
    var form = new formidable.IncomingForm();
    form.parse(req, function(err,fields,files){
        var oldpath = files.filetoupload.path;
        var newpath = 'C://xampp/htdocs/nodejs/upload/' + files.filetoupload.name;
        fs.rename(oldpath, newpath, function (err){
            if(err) throw err;
            res.write('File Uploaded and Moved !!');
            res.end();
        });
        res.write('File Uploaded');
        res.end();
    });
}
else{
    res.writeHead(200, {'Content-Type': 'text/html'}) ;
    res.write('<form action="fileUpload" method = "post" enctype="multipart/form-data">');
    res.write('<input type = "file" name="filetoupload" /><br/>') ;
    res.write('<input type="submit" />') ;
    res.write('</form>') ;
    return res.end() ;
    }
}).listen(8080) ;

我得到的错误是:

> Error [ERR_STREAM_WRITE_AFTER_END]: write after end
>     at write_ (_http_outgoing.js:572:17)
>     at ServerResponse.write (_http_outgoing.js:567:10)
>     at C:\xampp\htdocs\nodejs\upload.js:14:8
>     at FSReqWrap.args [as oncomplete] (fs.js:140:20) Emitted 'error' event at:
>     at writeAfterEndNT (_http_outgoing.js:634:7)
>     at process._tickCallback (internal/process/next_tick.js:63:19)

【问题讨论】:

    标签: javascript node.js file file-upload formidable


    【解决方案1】:

    您在关闭流后尝试写入。

    
        var form = new formidable.IncomingForm();
        form.parse(req, function(err,fields,files){
            var oldpath = files.filetoupload.path;
            var newpath = 'C://xampp/htdocs/nodejs/upload/' + files.filetoupload.name;
            fs.rename(oldpath, newpath, function (err){
                if(err) throw err;
                res.write('File Uploaded and Moved !!');
                res.end(); // here, remove this end call
            });
        });
    
    

    【讨论】:

    • 您是正确的,他在关闭流后正在写入,但不是在您指定的行。您指定的行在 fs.rename 的回调中,将在第二个 res.end 之后执行
    • 那么要删除哪一个? @r.delic
    • 知道了。 @LawrenceCherone。
    猜你喜欢
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 2014-09-11
    • 2017-08-30
    • 2020-07-16
    • 1970-01-01
    相关资源
    最近更新 更多