gpt4 book ai didi

java - 使用 volley 将图像上传到服务器,并在发布请求正文中包含多部分数据

转载 作者:太空宇宙 更新时间:2023-11-04 09:33:59 24 4
gpt4 key购买 nike

我正在尝试使用 volley 将图像上传到服务器,我遵循了一些教程,但就我而言,我需要在发布请求的正文中传递多部分数据。

   private void uploadBitmap(final Bitmap bitmap) throws JSONException {

//our custom volley request
String URL = "https://<---------->/me/avatar";

JSONObject jsonBody = new JSONObject();

jsonBody.put("avatar", new VolleyMultipartRequest.DataPart( "index.png", getFileDataFromDrawable(bitmap)));
final String requestBody = jsonBody.toString();
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, URL,
new Response.Listener<NetworkResponse>() {
@Override
public void onResponse(NetworkResponse response) {
loading.setVisibility(View.GONE);
Toast.makeText(ProfileSettings.this, "Image uploaded successfully", Toast.LENGTH_SHORT).show();
try {
JSONObject obj = new JSONObject(new String(response.data));

} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {


@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json; charset=UTF-8");
params.put("Authorization", "Bearer " + jsonToken);
return params;
}

@Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
long imagename = System.currentTimeMillis();
params.put("avatar", new DataPart(imagename + ".png", getFileDataFromDrawable(bitmap)));
return params;
}

@Override
public byte[] getBody() throws AuthFailureError {
return requestBody.getBytes();
}
};

//adding the request to volley
Volley.newRequestQueue(this).add(volleyMultipartRequest);
}

我从教程中得到了这段代码,但他们给出了 500 错误,所以我想这可能是因为我需要在请求正文中传递 "avatar": "index.png"而不是这样。

最佳答案

点击这些链接 - https://www.simplifiedcoding.net/upload-image-to-server/ https://www.simplifiedcoding.net/android-upload-image-to-server/

还可以使用此库上传图像和文件 - https://github.com/gotev/android-upload-service .

请按照上面的教程介绍这些库。

关于java - 使用 volley 将图像上传到服务器,并在发布请求正文中包含多部分数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56740258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com