Android使用HttpURLConnection实现文件上传(包括图片)

1.文件上传完整代码

下面是完整的文件上传代码,复制即可使用。注意要开启子线程运行

public class UploadFileTask {
    /**
     * 上传文件到服务器,并返回服务器相应结果
     * @param requestURL 服务器的地址
     * @param imageUri 文件的Uri
     * @param context
     * @return 服务器返回的结果
     */
    public String uploadFile(String requestURL, Uri imageUri, Context context) {
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        InputStream inputStream = null;

        String boundary = "*****" + System.currentTimeMillis() + "*****";
        String lineEnd = "\r\n";
        String twoHyphens = "--";

        try {
            InputStream fileInputStream = context.getContentResolver().openInputStream(imageUri);
            URL url = new URL(requestURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                    + imageUri.getLastPathSegment() + "\"" + lineEnd);
            outputStream.writeBytes(lineEnd);

            int bytesAvailable = fileInputStream.available();
            int bufferSize = Math.min(bytesAvailable, 1024 * 1024);
            byte[] buffer = new byte[bufferSize];

            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer, 0, bufferSize)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            outputStream.flush();
            fileInputStream.close();
            outputStream.close();

            // 检查服务器响应
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            if (serverResponseCode == HttpURLConnection.HTTP_OK) {
                inputStream = connection.getInputStream();
                String result = convertStreamToString(inputStream);
                Log.d("Upload Success", "Response: " + result);
                inputStream.close();

                return result;
            } else {
                Log.d("Upload Error", "Response Code: " + serverResponseCode + " Message: " + serverResponseMessage);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
        return "";
    }

    private String convertStreamToString(InputStream is) {
        Scanner s = new Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }
}

2.测试文件上传效果

有时候我们可能没有后台服务器来测试上传效果,这时候我们可以使用postman提供的测试URL,具体看这篇文章:测试图片上传功能,使用postman提供的url

  • 20
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值