Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

how to upload file in node js

router.post('/upload', function(req, res) {
    
    let valid_response = {
        status: true
    };

    if (!req.files || Object.keys(req.files).length === 0) {
        valid_response['status'] = false;
        valid_response['message'] = 'No files were uploaded.';

        return res.status(400).send(valid_response);
    }

    // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
    let sampleFile = req.files.file;

    // Use the mv() method to place the file somewhere on your server
    sampleFile.mv(__dirname + '/../media/' + sampleFile.name, function(err) {
        if (err)
            return res.status(500).send(err);

        valid_response['file'] = sampleFile.name;
        valid_response['file_type'] = sampleFile.mimetype;
        return res.send(valid_response);
    });
});
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #upload #file #node #js
ADD COMMENT
Topic
Name
5+8 =