NodeJS Web App File Upload Chops Off Beginning Of File

随声附和 提交于 2019-12-04 13:34:45

问题


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!!!!');
        });
    }
});

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.

Thanks!


回答1:


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.




回答2:


I am having this exact same problem. It bothers me that having too much logic between the request and the on('data') event is the problem. I"m testing with a local server, and the amount of logic between the start of the request and registering the on data event is negligible. But the fact that I don't need to cross the internet to do my upload is making this problem that much worse? Are you still experiencing this issue?



来源:https://stackoverflow.com/questions/7065042/nodejs-web-app-file-upload-chops-off-beginning-of-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!