NodeJS Web应用程序文件上传砍掉文件头应用程序、文件上传、文件、NodeJS

2023-09-10 16:15:40 作者:寒夜々孤星

我工作的NodeJS项目涉及文件上载。上载在与code中的客户端完成的:

I'm working on a project in NodeJS which involves file upload. The upload is done on the client side with the code:

$('#file-upload').bind('change focus click', function() {
    var file = jQuery(this)[0].files[0];
    if (file && file.fileName) {
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener('progress', onProgressHandler, false);
        xhr.upload.addEventListener('load', transferComplete, false);
        xhr.open('POST', '/upload', true);
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.setRequestHeader('X-File-Name', encodeURIComponent(file.fileName));
        xhr.setRequestHeader('Content-Type', 'application/octet-stream');
        xhr.send(file);


        function onProgressHandler(evt) {
            var percentage = event.loaded/event.total*100;
            console.log(percentage);
        }
        function transferComplete(evt) {
            console.log('Done');
        }
    }
});

而在服务器端,我用的:

And on the server-side, I use:

app.post('/upload', function(req, res, next) {
    if(req.xhr) {
        console.log('Uploading...');
        var fName = req.header('x-file-name');
        var fSize = req.header('x-file-size');
        var fType = req.header('x-file-type');
        var ws = fs.createWriteStream('./'+fName)

        req.on('data', function(data) {
            console.log('DATA');
            ws.write(data);
        });
        req.on('end', function() {
            console.log('All Done!!!!');
        });
    }
});

这code不单独工作,但与我大很多项目的其余部分相结合,似乎砍大文件的开始,而忽略小文件都在一起。如果我上传一个小文件时,执行console.log(数据)永远不会触发,它会触发大文件,而不是为文件的开头。我相信,由于某种原因,它是早期和我的功能它拾起开始的时间发送文件(或一个小文件的情况下,整个事情)已经发送。我不知道会是什么造成这一点,虽然。

This code does work alone, but when combined with the rest of my much larger project, it seems to chop of the beginning of large files, and ignore small files all together. If I upload a small file, the console.log('DATA') never fires and it does fire for large files, but not for the beginning of the file. I believe for some reason it is sending the file early and by the time my function picks it up the beginning (or in the case of a small file, the entire thing) has already sent. I don't know what would be causing this, though.

谢谢!

推荐答案

我想它了。有我的路线之间如此多的逻辑被定义和实际文件上载code运行,这是没有准备好倾听文件。

I figured it out. There was so much logic between my route being defined and the actual file upload code running that it wasn't ready listening for the file.