How to fix an Android application 400 error when uploading files on the Flask server
I’m trying to upload a file from an android app to a flask server using httpclient. I keep getting 400 bad requests from the 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 use curl file upload correctly
curl -i -F filedata=@”/home/rino/test.pcm”http://127.0.0.1:5000/audiostream
The server is configured as
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
think my mistake is trivial, but I can’t recognize it.
Solution
When a key in a request cannot be accessed, Flask throws a 400 Bad Request. My guess (just by looking at the code) is that you are trying to extract request.files['filedata']
but it is not present in the Java request.
But it does in curl request -F filedata
.
Try this: Http POST in Java (with file upload). It shows an example of how to add sections to a form upload using HttpClient and HttpPost.
According to this post you may also need to add” multipart/form-data”.
tl; dr – Flask is requesting a dictionary to look up the file data key and you are not sending it.