0

I have a client side component that produces a DataURL (i.e. a user uploads or snaps a picture and then crops it). I need to post that via an AJAX call to a sails endpoint. From the sails docs, the endpoint is supposed to read the files like so:

req.file('file_name');

I am stuck on how I am supposed to go from DataURI -> AJAX call formatted so that the endpoint will be able to read the file from req.file. I guess I just need to see an implementation of the call being setup in any javascript/framework library so that I can implement.

Thanks a lot.

pQuestions123
  • 4,471
  • 6
  • 28
  • 59

1 Answers1

1

On the client-side you'll need to convert the DataURL into form data. There are a couple examples here and here and send it to the route in your controller.

Your endpoint will be a route that looks a bit like this:

  var uploadHandlier = function(req, res)
  {

        req.file('avatar').upload(
        {
              // don't allow the total upload size to exceed ~4MB
              maxBytes: 4000000,
              dirname: '/tmp' // some temp directory
        }, function whenDone(error, uploadedFiles)
        {
              if (error)
              {
                    if (error.code === 'E_EXCEEDS_UPLOAD_LIMIT')
                    {
                          return res.badRequest(
                          {
                                msg: error.message
                          });
                    }

                    return res.serverError(error);
              }

              if (_.isEmpty(uploadedFiles))
              {
                    res.badRequest(
                    {
                          msg: "No file was uploaded."
                    });
                    return;
              }

              var filePath = uploadedFiles[0].fd;
              var fileType = uploadedFiles[0].type;

              if (!_.includes(['image/jpeg', 'image/png', 'image/gif'], fileType))
              {
                    res.badRequest(
                    {
                          msg: "Invalid file type."
                    });

                    return;
              }

              // do your thing...

        });
  };
Community
  • 1
  • 1
Matt Wielbut
  • 2,584
  • 25
  • 29