簡體   English   中英

如何解決 400 statusCode 和 Unexpected character (at character 1) 錯誤?

[英]How to solve 400 statusCode and Unexpected character (at character 1) error?

I have a machine learning model that takes a picture and returns a prediction, I uploaded it to a flask server and tested it on website that I created using HTML and it worked, but when I try to use it with a flutter app I get this錯誤:未處理的異常:FormatException:當我嘗試從我的應用程序上傳圖片時出現意外字符(在字符 1 處) 另外,我得到的 statusCode 是 400 .. 這些是我的代碼。 任何幫助將非常感激。

這是我的 python 代碼,我在其中創建了 flask 實例(當我嘗試使用 cmd 建立連接時,我在 cmd 上運行它)

from flask import Flask, render_template, request, jsonify
import cv2
import numpy as np
import pandas as pd
import tensorflow
from tensorflow import keras
from tensorflow.python.keras import backend as k

app = Flask(__name__)

model = tensorflow.keras.models.load_model('model.h5')


@app.route('/')
def index():
    return render_template("index.html", data="hey")


@app.route("/prediction", methods=["POST"])
def prediction():

    
    img = request.files['img']  
    img.save("img.jpg")
    image = cv2.imread("img.jpg")
    image = cv2.resize(image, (224,224))
    image = np.reshape(image, (1,224,224,3))
    pred = model.predict(image)

    pred = pred > 0.5
    if(pred):
        predd="Malignant"
    else:
        predd="Benign"

    return jsonify({"prediction": predd,})
    
#this ip is my network's IPv4
#(I connected both my laptop and mobile to this WiFi while establishing the connection)
if __name__ == "__main__":
    app.run(debug=False,host='192.168.1.103',port=5000)

這是我在 flutter 中用於建立連接的代碼

  sendImageToServer(File imageFile) async {
    var stream = new http.ByteStream(imageFile.openRead());
    stream.cast();
    var length = await imageFile.length();
    print(length);
    
    //this ip is my network's IPv4 
    //(I connected both my laptop and mobile 
    //to this WiFi while establishing the connection) 

    var uri = Uri.parse('http://192.168.1.103:5000/prediction');
    var request = new http.MultipartRequest("POST", uri);
    var multipartFile = new http.MultipartFile('file', stream, length,
        filename:
            basename(imageFile.path));

    request.files.add(multipartFile);
    request.headers["Content-Type"] = 'multipart/form-data';
    var streamedResponse = await request.send();
    var response = await http.Response.fromStream(streamedResponse);
    
    print(response);

    final Map<String, dynamic> responseJson =
        json.decode(response.toString()) as Map<String, dynamic>;
    print(responseJson.toString());

    pre = responseJson["prediction"];
    print(pre);

    setState(() {
      prediction = pre;
    });
  }

  Future getImage() async {
    final image = await picker.getImage(source: ImageSource.gallery);
    sendImageToServer(File(image.path));

    setState(() {
      fileImage = File(image.path);
      sendImageToServer(fileImage);
    });
  }

這也是我在發送請求時在 cmd 上得到的

192.168.1.108 - - [20/Mar/2021 19:14:39] "←[1m←[31mPOST /prediction HTTP/1.1←[0m" 400 -

更新的答案

所以你得到的例外是告訴你服務器無法理解你發送的請求,我認為現在的問題是你在這里發送請求的關鍵

var multipartFile = new http.MultipartFile('file', stream, length,
        filename:
            basename(imageFile.path));

在您的后端,您正在使用密鑰“img”

img = request.files['img']  

所以這些應該是一樣的,試試下面

var multipartFile = new http.MultipartFile('img', stream, length,
        filename:
            basename(imageFile.path));

我真的希望這會起作用,還請查看以下鏈接,它可能會幫助您更多地了解問題,

https://dev.to/carminezacc/advanced-flutter-networking-part-1-uploading-a-file-to-a-rest-api-from-flutter-using-a-multi-part-form-data-請求后 2ekm

這個stackoverflow問題

舊答案

錯誤消息沒有說明錯誤的確切位置,請在 try catch 塊中添加您的代碼,這樣您就可以捕獲任何拋出的異常並知道錯誤是什么。

try {
sendImageToServer(File imageFile) async {
    var stream = new http.ByteStream(imageFile.openRead());
    stream.cast();
    var length = await imageFile.length();
    print(length);
    
    //this ip is my network's IPv4 
    //(I connected both my laptop and mobile 
    //to this WiFi while establishing the connection) 

    var uri = Uri.parse('http://192.168.1.103:5000/prediction');
    var request = new http.MultipartRequest("POST", uri);
    var multipartFile = new http.MultipartFile('file', stream, length,
        filename:
            basename(imageFile.path));

    request.files.add(multipartFile);
    request.headers["Content-Type"] = 'multipart/form-data';
    var streamedResponse = await request.send();
    var response = await http.Response.fromStream(streamedResponse);
    
     //print(response);//this will print instance of response not the response itself
     // i cleared this a bit so we can trace where the error started from
     print(response.statusCode); // the status code of your response
     print(response.reasonPhrase); // the reason it failed "in case it did"
     print(response.body); // the body of the response -> this what you really interested in

  }
} catch (e,s) {
  // this is your life saver, it will tell you everything 
  // you need to know to trace the error (well mostly :D)
  // note : this will catch any exceptions that is thrown in the code, this not related to the response
  // the (e) is error it self so your should print that to know what is the error
  print(e.toString());
  // the (s) is the stackTrace, it will tell you when and where the error 
  // happened, so you should also print it
  print(e.toString());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM