无法将图像上传到经过改造的服务器



我目前正在进行一个个人项目,我想在该项目中将个人资料图片上传到我的服务器。我可以通过邮递员将图像以表单数据的形式发送到服务器上,但当我进行同样的改造时,它不起作用,有时它会创建一个1kb的文件,打开时会显示错误。

我目前正在做的是

Uri uri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
profileImage.setImageBitmap(bitmap);


File file = new File(uri.getPath());
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"),file);
MultipartBody.Part body = MultipartBody.Part.createFormData("Profile", "bcs.jpeg", reqFile);
authViewModel.setNewProfilePic(layout,email,body);

并且用于setNewProfilePic的代码是

public void setNewProfilePic(RelativeLayout relativeLayout, String email,MultipartBody.Part part) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
api = new Retrofit.Builder().baseUrl(Constants.URL_API).client(client).build().create(SpendistryAPI.class);
retrofit2.Call<okhttp3.ResponseBody> req = api.setNewProfilePic(email,part);
req.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
// Do Something
if (!response.isSuccessful()) {
Toast.makeText(application, "notWorking: " + response.code(), Toast.LENGTH_SHORT).show();
return;
}
try {
Toast.makeText(application, response.body().string(), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(application, "catch", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});

如果我向RequestBody.create提供文件,比如

File file = new File(uri.getPath());
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"),file);

设置新配置文件pic的代码不会被执行,如果我在.create((方法id中只传递URI.getPath((,则会在服务器上创建1kb的无法打开的图像文件。

请帮我处理这种情况,提前谢谢!!

我认为您可能没有授予读取外部存储权限,uri.getPath((将不起作用,您必须从uri中找到一个真正的路径才能使用此代码

private String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(this, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}

现在,将这个字符串传递到文件中,否则代码就是完美的!

FILE file = new file(getRealPathFromURI(uri));

相关内容

最新更新