Search code examples
pythonangularjsionic-frameworkflaskcordova-plugins

Sending image to Python Backend - Cordova File Transfer


I'm trying to send an image from the client side (Ionic Framework) to my Python Backend (Flask). For some reason, I keep getting Error Code 3 which I understand is a Connection Error, but I'm not sure why.

Client Side Code (AngularJS):

    $scope.submit = function() {
       if($scope.details.title === '' || $scope.details.price === '' || $scope.details.description === ''
        || $scope.details.category === '') {
            ionicSuperPopup.show("Error!", "Fill out the appropriate fields!", "error");
       } else if($scope.size !== 2) {
          ionicSuperPopup.show("Error!", "You need to upload at least two images.", "error");
       } else {
          /* Post item to server, wait for success, and present success post. */
          //ItemFactory.addItem($scope.details);
          var url = 'http://127.0.0.1:5000/api/item/addItem';
          var name = $scope.details.images[0];
          var options = new FileUploadOptions();
          options.fileKey = 'image',
          options.fileName = name,
          options.chunkedMode = false,
          options.mimeType = 'image/jpg',
          options.params = { 'filename': name };
          options.headers = {
              Connection: "close"
          };

          var ft = new FileTransfer();
          ft.upload($scope.list[0], encodeURI(url), win, fail, options);
      } /* End of 'else' */
   } /* End of 'submit' */

$scope.list[0] contains the imageURI of the picture taken.

Backend Code:

    from flask_restful import reqparse, Resource

    class Item(Resource):
        parser = reqparse.RequestParser(bundle_errors=True) #All arguments must be present

        def post(self):
            Item.parser.add_argument('image', required=True, help="You need images.")
            args = Item.parser.parse_args()
            print("We have: {}".format(args))

Is there anything that I'm doing wrong? I feel like I've got everything covered, yet I don't understand why I have an error code 3. Thanks for the help!


Solution

  • So I actually figured out the problem. The image needs to be loaded as a file upload and I used werkzeug's FileStorage to do this:

      Item.parser.add_argument('file', required=True, help="You need image.", type=werkzeug.datastructures.FileStorage, location='files')