3

I'm trying to upload file from android app with httpclient to flask server. I'm always gets 400 bad request error from server

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'm using curl file uploads correctly curl -i -F filedata=@"/home/rino/test.pcm" http://127.0.0.1:5000/audiostream Server configuration is

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's uploading page"

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

So, I'm think that my mistake is trivial but I can't recognize it.

1 Answers1

3

Flask throws a 400 Bad Request when it can't access a key in the request. My guess (just by looking at the code) is that you're trying to pull out request.files['filedata'] but it doesn't exist in the Java request.

However it does in the curl request -F filedata.

Try taking a look at this: Http POST in Java (with file upload). It shows an example of how to add a part to your form upload using HttpClient and HttpPost.

According to this post you may need to add the encoding type of "multipart/form-data" as well.

tl;dr - Flask is looking for a filedata key in the request dict, you're not sending one.

Community
  • 1
  • 1
johnharris85
  • 17,264
  • 5
  • 48
  • 52
  • This happenes to me when I forget the "name" attribute in the tag of the file in the HTML must be the same as the key I try to access in flask. – F. Santiago Sep 09 '17 at 14:38