使用sockets,Android向Python发送图像文件

2024-10-01 13:24:55 发布

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

我正在尝试从android客户端向python服务器发送图像,我以前用python测试客户端和服务器实现了这一点。基本上,我的客户端应用程序采用由用户详细信息和图像组成的形式。一旦用户选择了图像,我就会在onActivityResult方法中获得uri并将其解析为如下所示的字符串

selectedImagePath = selectedImageUri.toString();

当用户点击表单上的submit按钮时,发送活动将被调用,表单数据作为一个包中数组中的额外数据。在

Bundle b=new Bundle(); b.putStringArray("regValues", new String[]{name,email,selectedImagePath});

在发送活动中,我建立了与服务器的连接,并尝试像这样发送图像。在

在` //与服务器建立链接

    try{

     //refer to the host computer's loopback interface
     host = InetAddress.getByName("10.0.2.2"); 
     link = new Socket(host,port);
     in = new BufferedReader(new InputStreamReader(link.getInputStream()));

     //access the strings that were passed to this activity 
     Bundle b = this.getIntent().getExtras();
     String[] regFormValues = b.getStringArray("regValues");

     //display connection confirmation

     String message = in.readLine();
     status.setText(message);



        File myFile = new File (regFormValues[2]);
        byte [] mybytearray  = new byte [(int)myFile.length()];
        FileInputStream fis = new FileInputStream(myFile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        bis.read(mybytearray,0,mybytearray.length);
        OutputStream os = link.getOutputStream();

        os.write(mybytearray,0,mybytearray.length);
        os.flush();
        link.close();





    }
    catch(IOException e ){

     e.printStackTrace();

    }
    `

它连接到服务器没问题 服务器为输出创建一个文件,以便像往常一样将数据写入其中,但它只是显示为空,因此没有数据被接收。我想可能是客户端的文件路径有问题。有什么想法吗?在

编辑:基本上我想知道我是否以正确的方式访问图像文件,或者您是否有更好的访问和发送建议。在


Tags: 数据用户图像服务器host客户端newstring
2条回答

考虑使用诸如文件.exists()和文件.isFile()验证路径是否正常以及映像是否确实存在

还要检查图像是否碰到电线-使用tcpdump ro wireshark

我已经解决了这个问题,因为我use selectedImageUri = Uri.fromFile(photo);如果它是由相机拍摄的,那么selectedImageUri = data.getData();如果它是由文件浏览器选择的,那么就得到它。我使用selectedImagePath = selectedImagePath.substring(7);将文件://从相机的图像路径中剥离出来,生成一个/sdcard/etc或存储它的任何地方。为了获得文件浏览器选择的图像的文件路径,我使用了

// convert the image URI to the direct file system path of the image file  
public String getRealPathFromURI(Uri contentUri) {  

    // can post image  
    String [] proj={MediaStore.Images.Media.DATA};  
    Cursor cursor = managedQuery( contentUri,  
            proj, // Which columns to return  
            null,       // WHERE clause; which rows to return (all rows)  
            null,       // WHERE clause selection arguments (none)  
            null); // Order-by clause (ascending by name)  
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);  
    cursor.moveToFirst();  

    return cursor.getString(column_index);  

现在它像预期的那样工作。在

相关问题 更多 >