Skip to main content
 首页 » 编程设计

android之将图像从 Android 上传到 Python 服务器

2025年05月04日36davidwang456

我想知道在 Python 中使用什么库或框架来读取 Android 客户端发布的图像。

所以基本上,Android 客户端在手机中获取一个图像文件并发送它 通过 POST 请求到 Python 服务器。在 Python 中读取图像时,我唯一读到的是通过套接字。

我想询问有关如何实现 Python 服务器端以通过 POST 读取图像的链接或一些示例代码。

请您参考如下方法:

我有一个基于 python-flask 的后端网络应用程序,它有这种方法来接受图像。

@app.route('/getNoteText',methods=['GET','POST']) 
def GetNoteText(): 
    if request.method == 'POST': 
        file = request.files['pic'] 
        filename = file.filename 
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 
        processImage(filename)             
    else: 
        return "Y U NO USE POST?" 

我调用这个方法的 android 函数看起来像这样

  /** 
     * Uploading the file to server 
     */ 
    private class UploadFileToServer extends AsyncTask<Void, Integer, String> { 
        @Override 
        protected void onPreExecute() { 
            super.onPreExecute(); 
        } 
 
        @Override 
        protected String doInBackground(Void... params) { 
            return uploadFile(); 
        } 
 
        private String uploadFile() { 
            String responseString = null; 
            Log.d("Log", "File path" + opFilePath); 
            HttpClient httpclient = new DefaultHttpClient(); 
            HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL); 
            try { 
                AndroidMultiPartEntity entity = new AndroidMultiPartEntity( 
                        new AndroidMultiPartEntity.ProgressListener() { 
 
                           @Override 
                          public void transferred(long num) { 
                                publishProgress((int) ((num / (float) totalSize) * 100)); 
                            } 
                        }); 
                ExifInterface newIntef = new ExifInterface(opFilePath); 
                newIntef.setAttribute(ExifInterface.TAG_ORIENTATION,String.valueOf(2)); 
                File file = new File(opFilePath); 
                entity.addPart("pic", new FileBody(file)); 
                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); 
                    Log.d("Log", responseString); 
                } else { 
                    responseString = "Error occurred! Http Status Code: " 
                            + statusCode + " -> " + response.getStatusLine().getReasonPhrase(); 
                    Log.d("Log", responseString); 
                } 
 
            } catch (ClientProtocolException e) { 
                responseString = e.toString(); 
            } catch (IOException e) { 
                responseString = e.toString(); 
            } 
 
            return responseString;     
        } 
    } 

这是文件上传 URL,它指的是我的 python 应用程序在上面创建的网络服务。

 public static final String FILE_UPLOAD_URL = "http://<localhost>:5000/getNoteText"; 

我们正在获取已拍摄并存储在 android 文件系统中的图像,并使用 UploadFileToServer 类,如下所示:

 String filePath = Environment 
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + 
                            File.separator + Config.IMAGE_DIRECTORY_NAME; 
                    File dirFile = mkDir(filePath); 
                    File outputFile = new File(dirFile, String.format("%d.png", System.currentTimeMillis())); 
                    outStream = new FileOutputStream(outputFile); 
 
                    outStream.write(data); 
                    outStream.close(); 
                    opFilePath = outputFile.getAbsolutePath(); 
                    UploadFileToServer uploadFileToServer = new UploadFileToServer(); 
                    uploadFileToServer.execute(); 

您可以使用此uploadFileToServer 将任何类型的文件发送到后台。您不必局限于图像。

希望这对您有所帮助!