HTTP File Upload Best Practices?

Viewed 25

I've created a file upload to an HTTP server that I'm not too happy with. I'm not sure about the security of the upload (along with other issues) and I'd appreciate some guidance on best practices :)

Working in a node env w/ js Client side:

var file = inputFies.files[0];
var formData = new FormData();
formData.append("file", file);
$.ajax({
    type: 'POST',
    url: 'http://ip:port/upload.xjs',
    data: formData,
    success: function(){
        //show upload successful
    },
    error: function(){
    //show upload failed
    },
    processData:false,
    contentType: false
});

And on server side:

var fs = require('fs');
var httpServer = http.createServer(function (request, response){
    var uri = url.parse(request.url).pathname;
    switch(uri)
    {
        case "upload.xjs":
            request.setEncoding('utf8');
            var passedHeader = false;
            var shorterData;
            var contentType;

            request.on('data', function(data) {
                if(passedHeader == false)
                {
                    passedHeader = true;
                    var headers = qs.parse(data.toString(), '\r\n', ':')
                    var fileInfo = headers['Content-Disposition'].split('; ');
                    
                    for (value in fileInfo)
                    {
                        if (fileInfo[value].indexOf("filename=") != -1)
                        {
                            fileName = fileInfo[value].substring(10, fileInfo[value].length-1)
                        }
                    }
                    contentType = headers['Content-Type'].substring(1);
                }

                var entireData = data.toString();

                //trim the data so we only have the raw contents of the file
                var upperBoundary = entireData.indexOf(contentType) + contentType.length + 2;
                var upperData = entireData.substring(upperBoundary);
                var lowerBoundary = upperData.indexOf("-------WebKitFormBoundary") - 2;
                shorterData = upperData.substring(2, lowerBoundary);
            });

            request.on('end', function(){
                fs.writeFile("dir/"+fileName, shorterData, (err) => {
                    if(err)
                    {
                        console.log(err);
                        response.end(err);
                    }
                    else
                    {
                        response.end("");
                    }
                });
            });
            break;
    }
});

I didn't test very long but it seems like the file that gets written is sometimes partial... in addition to that I'm wondering if I should encrypt the file that gets transferred? The server does need to store this file on its file system directly.

0 Answers
Related