Sails.js checking stuff before uploading files to MongoDB with skipper (valid files, image resizing etc)

前端 未结 2 828
南笙
南笙 2020-12-17 04:29

I\'m currently creating a file upload system in my application. My backend is Sails.js (10.4), which serves as an API for my separate front-end (Angular).

I\'ve cho

相关标签:
2条回答
  • 2020-12-17 05:15

    Ok, after fiddling with this for a while I've managed to find a way that seems to work.

    It could probably be better, but it does what I want it to do for now:

    upload: function(req, res) {
        var upload = req.file('file')._files[0].stream,
            headers = upload.headers,
            byteCount = upload.byteCount,
            validated = true,
            errorMessages = [],
            fileParams = {},
            settings = {
                allowedTypes: ['image/jpeg', 'image/png'],
                maxBytes: 100 * 1024 * 1024
            };
    
        // Check file type
        if (_.indexOf(settings.allowedTypes, headers['content-type']) === -1) {
            validated = false;
            errorMessages.push('Wrong filetype (' + headers['content-type'] + ').');
        }
        // Check file size
        if (byteCount > settings.maxBytes) {
            validated = false;
            errorMessages.push('Filesize exceeded: ' + byteCount + '/' + settings.maxBytes + '.');
        }
    
        // Upload the file.
        if (validated) {
            sails.log.verbose(__filename + ':' + __line + ' [File validated: starting upload.]');
    
            // First upload the file
            req.file('file').upload({}, function(err, files) {
                if (err) {
                    return res.serverError(err);
                }
    
                fileParams = {
                    fileName: files[0].fd.split('/').pop().split('.').shift(),
                    extension: files[0].fd.split('.').pop(),
                    originalName: upload.filename,
                    contentType: files[0].type,
                    fileSize: files[0].size,
                    uploadedBy: req.userID
                };
    
                // Create a File model.
                File.create(fileParams, function(err, newFile) {
                    if (err) {
                        return res.serverError(err);
                    }
                    return res.json(200, {
                        message: files.length + ' file(s) uploaded successfully!',
                        file: newFile
                    });
                });
            });
        } else {
            sails.log.verbose(__filename + ':' + __line + ' [File not uploaded: ', errorMessages.join(' - ') + ']');
    
            return res.json(400, {
                message: 'File not uploaded: ' + errorMessages.join(' - ')
            });
        }
    
    },
    

    Instead of using skipper-gridfs i've chosen to use local file storage, but the idea stays the same. Again, it's not as complete as it should be yet, but it's an easy way to validate simple stuff like filetype and size. If somebody has a better solution, please post it :)!

    0 讨论(0)
  • 2020-12-17 05:21

    You can specify a callback for the .upload() function. Example:

    req.file('media').upload(function (error, files) {
      var file;
    
      // Make sure upload succeeded.
      if (error) {
        return res.serverError('upload_failed', error);
      }
    
      // files is an array of files with the properties you want, like files[0].size
    }
    

    You can call the adapter, with the file to upload from there, within the callback of .upload().

    0 讨论(0)
提交回复
热议问题