【问题标题】:Issue in uploading image for prediction using a MultiPart POST Request使用 MultiPart POST 请求上传图像以进行预测时出现问题
【发布时间】:2022-11-06 19:32:34
【问题描述】:

该调用当前是通过 Flutter 应用程序进行的,该应用程序发出多部分 POST 请求。

颤振代码

var request = http.MultipartRequest(
      'POST',
      Uri.parse('https://techfarmtest.herokuapp.com/upload'),
    );
    Map<String, String> headers = {"Content-type": "multipart/form-data"};
    request.files.add(
      http.MultipartFile(
        widget.selectedImage.toString(),
        widget.selectedImage.readAsBytes().asStream(),
        widget.selectedImage.lengthSync(),
        filename: widget.selectedImage.path.split('/').last,
      ),
    );
    request.headers.addAll(headers);
    var res = await request.send();
    http.Response response = await http.Response.fromStream(res);
    var data = jsonDecode(response.body);
    return data;

我打算将图像上传到后端,然后执行预测并以 JSON 格式检索结果,后端使用脚本编写烧瓶.

烧瓶代码

@app.route('/upload',methods=["POST"])
def upload_image():
    if request.method == "POST":
        imageFile = request.files['image']
        fileName = werkzeug.utils.secure_filename(imageFile.filename)
        print('\nRecieved File name : ' + imageFile.filename)
        imageFile.save('./uploadedImages/' + fileName)
        pred('./uploadedImages/fileName')
def pred(sampleFile):
    model = load_model('./model.h5')
    # model.summary()
    sample_file = sampleFile
    sample_img = image.load_img(sample_file,target_size = (256,256,3))
    sample_img = image.img_to_array(sample_img)
    sample_img = np.expand_dims(sample_img,axis=0)


    prediction_arr = model.predict(sample_img)
    result = {
        'Sample' : str(sampleFile),
        'Label' : str(class_names[prediction_arr.argmax()]),
        'Confidence' : str(prediction_arr.max())
    }
    return jsonify(result)

我目前面临的问题是我提出了一个错误的请求(400)。这是我从各种资源中找出的粗略代码(伪代码)。有什么办法可以解决。

【问题讨论】:

    标签: python flutter flask heroku flask-restful


    【解决方案1】:

    所以,我自己想通了。

    我将附上下面的代码以供将来参考。

    颤振代码:

    var request = http.MultipartRequest(
         'POST',
         Uri.parse('https://techfarmtest.herokuapp.com/upload'),
    );
    request.files.add(
         await http.MultipartFile.fromPath('image', img.path),
    );
    var res = await request.send();
    

    您可以使用以下日志验证 POST 请求:

    log('${res.statusCode}', name: 'POST-request-statusCode');
    log('${res.reasonPhrase}', name: 'POST-request-status');
    

    关于 Flask :

    @app.route('/upload',methods=["POST","PUT"])
    def upload_image():
        if request.method == "POST":
            imageFile = request.files['image']
            ***you can perform any operation on the file you have recieved from the request now***
    

    谢谢!

    【讨论】:

      猜你喜欢
      • 2020-11-15
      • 2021-09-06
      • 1970-01-01
      • 2017-09-09
      • 2017-09-28
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 2016-08-25
      相关资源
      最近更新 更多