heroku 使用MultiPart POST请求上传图像进行预测时出现问题

0ejtzxu1  于 2022-11-13  发布在  其他
关注(0)|答案(1)|浏览(125)

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

Flutter代码

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格式检索结果,后端使用Flask编写脚本。

** flask 代码**

@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)。这是一个粗略的代码(伪代码),我已经从各种资源。有什么办法去它。

knsnq2tg

knsnq2tg1#

所以,我自己想出来的。
我将附上下面的代码供将来参考。
Flutter代码:

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***

谢谢你,谢谢你

相关问题