无法将图像从android上载到python flask服务器,请显示错误org.apache.http.连接主机异常在android中

2024-09-27 07:24:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Multipartentity将图像上传到python服务器。我收到来自服务器的错误is响应:org.apache.http.连接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);
    }

}

这是url

public String UPLOAD_URL=“http://192.168.0.104:5000/static/android

这是植物编码

^{pr2}$

但你写的附加代码是

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

你为什么要写这个代码。 上传图片需要这个代码吗?在


Tags: 代码httpnewstringreturnresponsenullentity
1条回答
网友
1楼 · 发布于 2024-09-27 07:24:49

我已经忘记了java和android的很多东西,但是错误可能来自最后一行的flask函数

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

您正在重定向到同一个URL,但它没有filename参数

签入flask doc about上载文件后,需要添加另一个方法来下载上载的文件并重定向到该方法

从文档中检查:

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:

并将upload_file方法的最后一行更改为:

^{pr2}$

并创建uploaded file方法:

from flask import send_from_directory

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

解决方案2:

或者,如果您只需要将图像保存在flask服务器中,您可以向用户返回一条成功消息,说明图像已保存。在

将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部分

还要确保您的flask应用程序运行在192.168.0.104和端口5000上

相关问题 更多 >

    热门问题