How to fix error 400 when uploading files to flask server from Android app

I am trying to upload a file from android application using httpclient to flash server. I always get 400 server error errors

public String send()
{
    try {
        url = "http://192.168.1.2:5000/audiostream";
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "/test.pcm");
        Log.d ("file" , file.getCanonicalPath());
        try {

            Log.d("transmission", "started");
            HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost(url);
            ResponseHandler Rh = new BasicResponseHandler();

            InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
            reqEntity.setContentType("binary/octet-stream");
            reqEntity.setChunked(true); // Send in multiple parts if needed

            httppost.setEntity(reqEntity);
            HttpResponse response = httpclient.execute(httppost);

            response.getEntity().getContentLength();
            StringBuilder sb = new StringBuilder();
            try {
                BufferedReader reader =
                        new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 65728);
                String line;

                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
            }
            catch (IOException e) { e.printStackTrace(); }
            catch (Exception e) { e.printStackTrace(); }


            Log.d("Response", sb.toString());
            Log.d("Response", "StatusLine : " + response.getStatusLine() + " Entity: " + response.getEntity()+ " Locate: " + response.getLocale() + " " + Rh);
            return sb.toString();
        } catch (Exception e) {
            // show error
            Log.d ("Error", e.toString());
            return e.toString();
        }
    }
    catch (Exception e)
    {
        Log.d ("Error", e.toString());
        return e.toString();
    }

}

      

But when I load the curl file correctly curl -i -F filedata = @ "/home/rino/test.pcm" http://127.0.0.1:5000/audiostream Server config

import os
from werkzeug.utils import secure_filename
from flask import Flask, jsonify, render_template, request, redirect,         url_for, make_response, send_file, flash
app = Flask(__name__)
app.debug = True


UPLOAD_FOLDER = '/home/rino/serv'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/audiostream',methods=['GET', 'POST'])
def audiostream():
if request.method == 'POST':
    file = request.files['filedata']
    filename = secure_filename(file.filename)
    fullpath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    file.save(fullpath)
    return jsonify(results=['a','b'])

if request.method == 'GET':
    return "it uploading page"

if __name__ == "__main__":
    app.run(host='0.0.0.0')

      

So, I think my mistake is trivial, but I cannot recognize it.

+3


source to share


1 answer


Flask throws 400 Bad Request when it cannot access the key in the request. My guess (just by looking at the code) is that you are trying to pull request.files['filedata']

, but it doesn't exist in the Java request.

However, this is done in the curl request -F filedata

.

Try looking at this: Http POST in Java (with file upload) . It shows an example of adding a part to load a form using HttpClient and HttpPost.



As per this post, you may need to add the "multipart / form-data" encoding type.

tl; dr - Flask looks for the filedata key in the dict request, you don't send it.

+3


source







All Articles