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服务器总是失败的问题。

相关内容

热门资讯

信息共享!大懒人斗十四辅助(透... 信息共享!大懒人斗十四辅助(透视)大菠萝辅助器(德州论坛有挂讲解);无需打开直接搜索加薇136704...
一分钟了解!乐酷辅助图片(透视... 一分钟了解!乐酷辅助图片(透视)拱趴大菠萝挂(透明教程有挂秘籍);无需打开直接搜索打开薇:13670...
透视软件!椰岛常胜辅助器(透视... 您好:hhpoker软件安装包这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...
2024教程!wepoker透... 2024教程!wepoker透视脚本免费(透视)wepoker安装教程(分享教程有挂详细);无需打开...
每日必备!欢乐对决脚本(透视)... 每日必备!欢乐对决脚本(透视)hhpoker辅助软件(德州教程有挂猫腻)您好:hhpoker辅助软件...
查到实测!浙江宝宝游戏辅助器哪... 浙江宝宝游戏辅助器哪里能下载 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四...
玩家必备攻略!广东闲来辅助软件... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
透视智能ai!相约十三张辅助(... wepoker私人局俱乐部怎么进 无需打开直接搜索微信:136704302本司针对手游进行,选择我们...
揭秘几款!如何设置钱塘十三水辅... 揭秘几款!如何设置钱塘十三水辅助器(透视)wepoker有机器人吗(2026新版有挂方针);无需打开...
透视辅助!威胁你小程序雀神挂件... 透视辅助!威胁你小程序雀神挂件(透视)wejoker手机版透视脚本(2026版教程有挂存在) 了解更...