我正尝试使用齐射将图像上传到服务器,我遵循了一些教程,但就我而言,我需要在发布请求的正文中传递多部分数据。
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”,而不是这种方式。>
答案 0 :(得分:0)
关注这些链接-https://www.simplifiedcoding.net/upload-image-to-server/ https://www.simplifiedcoding.net/android-upload-image-to-server/
,还使用该库上传图像和文件-https://github.com/gotev/android-upload-service。
请按照上面的教程介绍这些库。
答案 1 :(得分:0)
我能够通过改装2实现这一点,这是代码。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
//getting the image Uri
Uri imageUri = data.getData();
try {
//getting bitmap object from uri
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
//displaying selected image to imageview
logo.setImageBitmap(bitmap);
//calling the method uploadBitmap to upload image
loading.setVisibility(View.VISIBLE);
///uploadBitmap(bitmap);
File file = new File(getRealPathFromUri(this, imageUri));
uploadImageFile(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private void uploadImageFile(File file) throws IOException {
file = new Compressor(this).compressToFile(file);
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
// MultipartBody.Part is used to send also the actual filename
MultipartBody.Part body = MultipartBody.Part.createFormData("avatar", file.getName(), requestFile);
ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
Call<ServerResponse> call = getResponse.uploadFile("Bearer "+jsonToken, body);
call.enqueue(new Callback< ServerResponse >() {
@Override
public void onResponse(@NonNull Call < ServerResponse > call, @NonNull retrofit2.Response<ServerResponse> response) {
ServerResponse serverResponse = response.body();
if (serverResponse.getData() != null) {
Log.e(TAG, "Response is "+ serverResponse.getData());
loading.setVisibility(View.GONE);
Toast.makeText(ProfileSettings.this, "Avatar updated", Toast.LENGTH_SHORT).show();
} else {
Log.e("Response", String.valueOf(serverResponse));
}
}
@Override
public void onFailure(Call < ServerResponse > call, Throwable t) {
Log.e(TAG, t.getMessage());
}
});
// Log.e(TAG, "request is "+call.request().body()+" and "+call.request().headers());
}