簡體   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

我正在使用 Multipartentity 將圖像上傳到 python 服務器。 我收到一個錯誤是來自服務器的響應:org.apache.http.conn.HttpHostConnectException:連接到http://192.168.0.104:5000 被拒絕。 可以解釋任何人,為什么會出現錯誤?

這是后端任務代碼:

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);
    }

}

這是網址

公共字符串 UPLOAD_URL = " http://192.168.0.104:5000/static/android ";

這是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))

但你寫的額外代碼是,

@app.route('/uploads/<filename>')
def uploaded_file(filename):
   return send_from_directory(app.config['UPLOAD_FOLDER'],
                           filename) 

你為什么寫這段代碼。 上傳圖片是否需要此代碼?

我從 java 和 android 中忘記了很多,但錯誤可能來自最后一行的flask函數

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

您正在重定向到相同的 URL 並且它沒有文件名參數

在檢查flask doc關於上傳文件后,您需要添加另一種下載上傳文件的方法並重定向到該方法

從文檔中檢查:

現在缺少最后一件事:上傳文件的服務。 在upload_file()中,我們將用戶重定向到url_for('uploaded_file', filename=filename),即/uploads/filename。 所以我們編寫了uploaded_file() 函數來返回該名稱的文件。 從 Flask 0.5 開始,我們可以使用一個為我們做這件事的函數:

並將 upload_file 方法的最后一行更改為:

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

並創建上傳文件的方法:

from flask import send_from_directory

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)

解決方案2:

或者,如果您只需要將圖像保存在燒瓶服務器中,您可以向用戶返回一條成功消息,說明圖像已保存。

將您的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 "

這僅適用於python部分

還要確保您的燒瓶應用程序在 192.168.0.104 和端口 5000 上運行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM