Я пытаюсь загрузить изображение в API, развернутый во Flask, который выполняет функцию post в python.Проблема в том, что, когда я пытаюсь вызвать функцию через почтальон, она работает отлично, но когда приходит на андроид, выдает ошибку
500-Internal Server Error
КогдаЯ проверяю логи колбы, которые я получаю
ИСКЛЮЧЕНИЕ: невозможно идентифицировать файл изображения <_io.BytesIO объект по адресу 0x00000013EBEDAF10> "
код Python на сервере:
@app.route('/image', methods=['POST'])
def predict_image_handler():
try:
imageData = None
if ('imageData' in request.files):
imageData = request.files['imageData']
elif ('imageData' in request.form):
imageData = request.form['imageData']
else:
imageData = io.BytesIO(request.get_data())
print("Data loaded")
img = Image.open(imageData)
print("Image open")
results = predict_image(img)
return jsonify(results)
except Exception as e:
print('EXCEPTION:', str(e))
return 'Error processing image', 500
Функция в Android, которая вызывает API:
private class UploadFileInTheBackground extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String upLoadServerUri ="http://10.1.0.51:5000/image" ;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String fileName = params[0];
try {
/**upload file start
*/
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(params[0]);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes("Content-Type: text/plain;charset=UTF-8" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" C:/xamp/wamp/fileupload/uploads";
messageText.setText(msg);
Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
/**uplod file end
*/
} catch (MalformedURLException e) {
Toast.makeText(MainActivity.this, "MalformedURLException.", Toast.LENGTH_SHORT).show();
}catch (FileNotFoundException e) {
Toast.makeText(MainActivity.this, "FileNotFoundException.", Toast.LENGTH_SHORT).show();
}catch (IOException ex) {
Toast.makeText(MainActivity.this, "IOException.", Toast.LENGTH_SHORT).show();
}
return "Done";
}
@Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
//txt.setText("Executed"); // txt.setText(result);
txt.setText(result);
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
}
@Override
protected void onPreExecute() {}
@Override
protected void onProgressUpdate(Void... values) {}
}