Monday, 14 June 2021

How to send images with axios using flask-python?

I'm trying to send an image using axios get method

I have tried the same using post request from axios

HTML

  <div>
    <form id="upImage" enctype="multipart/form-data">
      <input type="file" id="file" name="file">
      <input type=submit value=Upload onclick="uploadImage()">
      </form>

  </div>

    function uploadImage() {

      let image = $('#file').get(0);
      var formData = new FormData();
      formData.append('file', image.files[0]);
      axios({
        method: "post",
        url: "/imgUpload",  
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(function (response) {
          response_data = response.data["img_data"];
      });
    };

python

    @app.route('/imgUpload', methods=['POST'])
    def upload_image():
        file = request.files['file']
        filename = secure_filename(file.filename)
        file.save(os.path.join('/home/user/images', filename))
        return return jsonify({"img_data":102})

This change of method from post to get gives empty file.

    function uploadImage() {

      let image = $('#file').get(0);
      var formData = new FormData();
      formData.append('file', image.files[0]);
      axios({
        method: "get",
        url: "/imgUpload",  
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(function (response) {
          response_data = response.data["img_data"];
      });
    };



  'KeyError: 'file' and file will be empty.

How to replicate the same process using get request from axios?



from How to send images with axios using flask-python?

No comments:

Post a Comment