I'm using Multipartentity for uploading image to python server. I got an error is Response from server: org.apache.http.conn.HttpHostConnectException: Connection to http://192.168.0.104:5000 refused. Can explain anyone, why this come error?
This is the backend task code:
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
long totalSize = 0;
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
// setting progress bar to zero
progressDialog = new ProgressDialog(RegisterActivity.this);
progressDialog.show();
}
@Override
protected String doInBackground(Void... params) {
return uploadFile();
}
@SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
@Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
String imagefilepath = null;
String filemanagerstring = filePath.getPath();;
String selectedImagePath = getPath(filePath);
if (selectedImagePath != null) {
imagefilepath = selectedImagePath;
} else if (filemanagerstring != null) {
imagefilepath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
File sourceFile = new File(imagefilepath);
// Adding file data to http body
entity.addPart("aadharimage", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
Log.e(TAG, "Response from server: " + result);
progressDialog.dismiss();
// showing the server response in an alert dialog
super.onPostExecute(result);
}
}
This is the url
public String UPLOAD_URL = " http://192.168.0.104:5000/static/android ";
This is the phyton code
@app.route('/static/android', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['aadharimage']
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file :
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
but you have written the additional code is,
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
why did you write this code. is this code is necessary to upload images?
I've forgotten a lot from java and android, but the error may come from your flask function on the last line
return redirect(url_for('upload_file', filename=filename))
you are redirecting to the same URL and it doesn't have a filename argument
After checking in flask doc about uploading file, you need to add another method for download the uploaded file and redirect to that one
check this from the doc:
Now one last thing is missing: the serving of the uploaded files. In the upload_file() we redirect the user to url_for('uploaded_file', filename=filename), that is, /uploads/filename. So we write the uploaded_file() function to return the file of that name. As of Flask 0.5 we can use a function that does that for us:
And change the last line of your upload_file method to this :
return redirect(url_for('uploaded_file', filename=filename))
And create the uploaded file method :
from flask import send_from_directory
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
SOLUTION 2 :
Or If you just need to save the image in the flask server you could return a success message to the user saying that the image was saved.
change your python code to this :
@app.route('/static/android', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
print request
print request.values
# check if the post request has the file part
if 'file' not in request.files:
# flash('No file part')
return redirect(request.url)
print(request.files['aadharimage'])
file = request.files['aadharimage']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
print(file)
# flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
print(file)
print(file.filename)
filename = secure_filename(file.filename)
# print filename
print(app.config['UPLOAD_FOLDER'])
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return "an image has been saved "
This is only for the python part
Also Make sure that your flask app is running on 192.168.0.104 and port 5000
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.