简体   繁体   English

无法将图像从android上传到python Flask服务器,在android中显示错误org.apache.http.conn.HttpHostConnectException

[英]unable to upload image from android to python flask server, show the error org.apache.http.conn.HttpHostConnectException in android

I'm using Multipartentity for uploading image to python server.我正在使用 Multipartentity 将图像上传到 python 服务器。 I got an error is Response from server: org.apache.http.conn.HttpHostConnectException: Connection to http://192.168.0.104:5000 refused.我收到一个错误是来自服务器的响应:org.apache.http.conn.HttpHostConnectException:连接到http://192.168.0.104:5000 被拒绝。 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 ";公共字符串 UPLOAD_URL = " http://192.168.0.104:5000/static/android ";

This is the phyton code这是phyton代码

@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我从 java 和 android 中忘记了很多,但错误可能来自最后一行的flask函数

return redirect(url_for('upload_file', filename=filename))

you are redirecting to the same URL and it doesn't have a filename argument您正在重定向到相同的 URL 并且它没有文件名参数

After checking in flask doc about uploading file, you need to add another method for download the uploaded file and redirect to that one在检查flask doc关于上传文件后,您需要添加另一种下载上传文件的方法并重定向到该方法

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.在upload_file()中,我们将用户重定向到url_for('uploaded_file', filename=filename),即/uploads/filename。 So we write the uploaded_file() function to return the file of that name.所以我们编写了uploaded_file() 函数来返回该名称的文件。 As of Flask 0.5 we can use a function that does that for us:从 Flask 0.5 开始,我们可以使用一个为我们做这件事的函数:

And change the last line of your upload_file method to this :并将 upload_file 方法的最后一行更改为:

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 :解决方案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 :将您的python代码更改为:

@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这仅适用于python部分

Also Make sure that your flask app is running on 192.168.0.104 and port 5000还要确保您的烧瓶应用程序在 192.168.0.104 和端口 5000 上运行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android Studio错误org.apache.http.conn.HttpHostConnectException:拒绝与http://10.0.2.2:8080的连接 - Android Studio error org.apache.http.conn.HttpHostConnectException: Connection to http://10.0.2.2:8080 refused org.apache.http.conn.HttpHostConnectException:拒绝连接到http:// localhost - org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused org.apache.http.conn.HttpHostConnectException:连接到127.0.0.1:7055 - org.apache.http.conn.HttpHostConnectException: Connect to 127.0.0.1:7055 错误:请求中的异常:org.apache.http.conn.HttpHostConnectException:与http:// ********:80的连接被拒绝 - ERROR:Exception in request: org.apache.http.conn.HttpHostConnectException: Connection to http://********:80 refused 在jmeter中收到错误“响应代码:非HTTP响应代码:org.apache.http.conn.HttpHostConnectException” - Getting an error “Response code: Non HTTP response code: org.apache.http.conn.HttpHostConnectException” in jmeter 从Eclipse访问URL时获取org.apache.http.conn.HttpHostConnectException - Getting org.apache.http.conn.HttpHostConnectException while accessing a URL from Eclipse org.apache.http.conn.HttpHostConnectException:连接到127.0.0.1:7055 [/127.0.0.1]失败:连接被拒绝:connect - org.apache.http.conn.HttpHostConnectException: Connect to 127.0.0.1:7055 [/127.0.0.1] failed: Connection refused: connect 线程“ main” org.apache.http.conn.HttpHostConnectException中的异常:连接到//失败:连接超时:connect - Exception in thread “main” org.apache.http.conn.HttpHostConnectException: Connect to // failed: Connection timed out: connect GitLab Runner 不一致:exec-maven-plugin:1.6.0:java org.apache.http.conn.HttpHostConnectException - GitLab Runner Inconsistency: exec-maven-plugin:1.6.0:java org.apache.http.conn.HttpHostConnectException Selenium 3.7:geckodriver:WebDriverException:org.apache.http.conn.HttpHostConnectException连接被拒绝 - Selenium 3.7 : geckodriver : WebDriverException: org.apache.http.conn.HttpHostConnectException Connection Refused
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM