使用OkHttp上传图片到服务器

3

我正在使用OKhttp进行网络请求。尝试将图像上传到服务器。这是我尝试的方法,但它并不起作用。我做错了什么?

client = new OkHttpClient.Builder()
                .build();

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] byteArray = stream.toByteArray();
        String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("", "",
                        RequestBody.create(MediaType.parse("image/*"), encodedImage))
                .build();

        Request request = new Request.Builder()
                .url(serverUrl)
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });
    }

1
"但它没有起作用":它是怎么“没有起作用”的?崩溃?没有连接?你必须更详细地描述,如果有崩溃,请添加日志记录。 - Zoe stands with Ukraine
如果你想更快地完成任务,请使用Volley。如果你真的需要帮助,请提供一些更多的细节,比如logcat。 - mrtpk
你为什么要对图像进行base64编码? - Jesse Wilson
在表单数据部分名称中使用空字符串也很可能是一个错误。 - Jesse Wilson
1个回答

4

您不需要对图像数据进行base64编码,只需使用byteArray即可:

.addFormDataPart("image", "filename.jpg",
                 RequestBody.create(MediaType.parse("image/*jpg"), byteArray))

那不是把整个位图都发送到网络上了吗? - Carson Holzheimer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接