无法从Android应用程序将文件上传到Flask

时间:2018-12-11 18:21:11

标签: android python flask

我正在尝试上传和映像到已部署到Flask的API中,后者正在python中运行发布功能。 问题是,当我尝试通过邮递员调用该函数时,效果很好,但是到android时会抛出错误

  

500-内部服务器错误

当我查看烧瓶上的日志时

  

例外:无法识别图像文件<_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) {}
}

0 个答案:

没有答案