Android上传图片到php服务器总是失败
创始人
2024-10-10 02:30:21
0

问题描述: 在Android开发中,我们经常需要将图片上传到php服务器,但是上传的过程中总是失败,无法成功上传图片。

解决方法:

  1. 确保Android端的权限设置正确。在AndroidManifest.xml文件中添加以下权限:


这些权限分别用于访问网络和读取SD卡上的图片。

  1. 确保Android端代码中的上传逻辑正确。以下是一个示例代码,用于将图片上传到php服务器:
public void uploadImage(String imagePath) {
    try {
        URL url = new URL("http://your_php_server_url/upload.php");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes("--" + boundary + "\r\n");
        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + imagePath + "\"" + "\r\n");
        dos.writeBytes("\r\n");

        FileInputStream fis = new FileInputStream(new File(imagePath));
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = fis.read(buffer)) != -1) {
            dos.write(buffer, 0, bytesRead);
        }
        fis.close();

        dos.writeBytes("\r\n");
        dos.writeBytes("--" + boundary + "--" + "\r\n");
        dos.flush();

        InputStream is = conn.getInputStream();

        // 处理服务器返回的结果
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        // 处理上传成功的逻辑
        if (response.toString().equals("uploaded_success")) {
            // 上传成功
        } else {
            // 上传失败
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

其中,imagePath为待上传图片的路径,your_php_server_url为php服务器的地址。该示例代码使用了HttpURLConnection来进行网络请求,并采用multipart/form-data的形式上传图片。

  1. 确保php服务器端的代码正确。以下是一个示例的php代码,用于接收并保存上传的图片:

在php代码中,我们将上传的图片保存到uploads/目录下,并根据上传结果返回不同的字符串。

通过以上三个步骤,我们可以解决Android上传图片到php服务器总是失败的问题。

相关内容

热门资讯

据报道!wepoker私人局有... 据报道!wepoker私人局有透视吗,智星德州有脚本吗,原来确实有挂(有挂教学)1、下载好智星德州有...
此事引发网友热议!hh pok... 此事引发网友热议!hh poker辅助有用吗,德普之星辅助软件,切实存在有挂(确实有挂)1、进入游戏...
代打辅助挂!wepoker游戏... 代打辅助挂!wepoker游戏的安装教程,德普之星透视,竟然是真的有挂(有挂透明挂)1、在德普之星透...
第三方技巧!sohoopoke... 第三方技巧!sohoopoker辅助,德扑之星透视辅助软件激活码,果然确实有挂(真的有挂)1、玩家可...
此事备受玩家关注!wepoke... 此事备受玩家关注!wepoker透视辅助下载,德普之星辅助器,原来存在有挂(有挂细节)1、每一步都需...
第三方技巧!xpoker辅助,... 第三方技巧!xpoker辅助,如何下载德普之星辅助软件,切实是有挂(有挂解密)1、上手简单,内置详细...
目前来看!wepoker私人局... 目前来看!wepoker私人局辅助器怎么用,德普之星辅助器怎么用,真是真的有挂(有人有挂)德普之星辅...
无独有偶!德普之星辅助工具如何... 无独有偶!德普之星辅助工具如何设置,德扑之星怎么设置埋牌,其实存在有挂(有挂技术)1、该软件可以轻松...
推出新举措!wpk刷入池率脚本... 推出新举措!wpk刷入池率脚本,德扑圈透视挂,本来真的是有挂(有挂猫腻)1)德扑圈透视挂辅助插件:进...
刚刚!poker world辅... 刚刚!poker world辅助,德扑之星私人局辅助免费,都是存在有挂(揭秘有挂)1、让任何用户在无...