无法通过okhttp填充flask中的request.files

qgelzfjb  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(396)

转换后,我将图像从imageview发送到flask服务器,但request.files为空。代码:

public void onFindCountButtonClicked(View view){
        String postUrl = "http://192.168.x.x:5000/";
        ImageView originalImage = findViewById(R.id.originalImage);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap = ((BitmapDrawable) originalImage.getDrawable()).getBitmap();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] byteArray = stream.toByteArray();
        RequestBody postBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("image", "androidFlask.jpg", RequestBody.create(MediaType.parse("image/*jpg"), byteArray)).build();
        postRequest(postUrl, postBody);
    }

private void postRequest(String postUrl, RequestBody postBodyText) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(postUrl).post(postBodyText).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                call.cancel();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TextView textView = findViewById(R.id.txtCount);
                        textView.setText("Connection failed");
                        densityMap = findViewById(R.id.densityMap);
                        densityMap.setImageBitmap(bitmap);
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TextView responseText = findViewById(R.id.txtCount);
                        try {
                            responseText.setText(response.body().string());
                        } catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

flask 代码:

import os
from flask import Flask, render_template, request, redirect, url_for
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = './static/'
ALLOWED_EXTENSIONS = set(['.jpg', '.jpeg'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        # Remove existing images in directory
        files_in_dir = os.listdir(app.config['UPLOAD_FOLDER'])
        filtered_files = [file for file in files_in_dir if file.endswith(".jpg") or file.endswith(".jpeg")]
        for file in filtered_files:
            path = os.path.join(app.config['UPLOAD_FOLDER'], file)
            os.remove(path)

        # Upload new file
        if 'file' not in request.files:
            return redirect(request.url)
        file = request.files['file']
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return "success" 
    return "failed"

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', threaded=True)

我总是“失败”。如果删除请求文件的if语句,则会在getitem raise exceptions.badrequestkeyerror(key)werkzeug.exceptions.badrequestkeyerror:400错误请求:浏览器(或代理)发送了此服务器无法理解的请求。keyerror:'文件'

suzh9iv8

suzh9iv81#

我用类似的东西。这是我用来将图像文件发送到flaskapi的代码。
发送图像文件代码:

import requests

with open("test.jpg", "rb") as imageFile:
    url = "https://YourUrl:port/endpoint"
    headers = {"Content-Type": "application/octet-stream"}
    response = requests.post(url, files=[("image_data", ("test.jpg", imageFile, "image/jpg"))])
    print(response.status_code)
    print(response.text)

api终结点代码:

@app.route('/endpoint', methods=["POST"])
def endpoint():
    img_bytes = request.files["image_data"].read()
    with open("temp.jpg", "wb") as file:
        file.write(img_bytes)

相关问题