当前位置: 首页 > 知识库问答 >
问题:

Android在使用改型多部件上传图像时有问题?

贾兴学
2023-03-14
userImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            galleryIntent.setType("*/*");
            startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
        }
    });

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {

        // Get the Image from data
        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        // Get the cursor
        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        // Move to first row
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        imageDecodableString = cursor.getString(columnIndex);
        cursor.close();

        StringBuilder stringBuilder = new StringBuilder(AUTHORIZATION);

        sharedPreferences = this.getSharedPreferences(getResources().getString(R.string.token), 0);
        stringBuilder.append(sharedPreferences.getString(getResources().getString(R.string.token), ""));

        methodMap.put("_method", "PUT");

        File file = new File(imageDecodableString);
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
        //RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "image");

        Call<UserInfo> uploadImage = new RestClient(CONSTS.BASE_URL_ADDRESS_ACCOUNT_CREATION).getUserSignUpClient()
                .postImage(stringBuilder.toString(), methodMap, body);

        uploadImage.enqueue(new Callback<UserInfo>() {
            @Override
            public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {

                if (response.isSuccessful()) {

                }

            }

            @Override
            public void onFailure(Call<UserInfo> call, Throwable t) {

                Toast.makeText(DetailActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();

            }
        });
    }

接口:

public interface UserSignUpClient {

@POST("account")
Call<AuthenticationAccountCreationResponse> createAccount(@Body UserSignUp userSignUp);

@Multipart
@POST("account")
Call<UserInfo> postImage(@Header("Authorization") String headerValue, @PartMap Map<String, String> map, @Part MultipartBody.Part image);
}

翻新生成器类:

public class RestClient {

private UserSignInClient userSignInClient;
private UserSignUpClient userSignUpClient;
private UserInfoClient userInfoClient;
private UserImageUploadClient userImageUploadClient;

public RestClient(String baseUrlLink){

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrlLink)
            .addConverterFactory(GsonConverterFactory.create()).build();

    if (baseUrlLink.equals(CONSTS.BASE_URL_ADDRESS_TOKEN)){

        userSignInClient = retrofit.create(UserSignInClient.class);
    } else if (baseUrlLink.equals(CONSTS.BASE_URL_ADDRESS_ACCOUNT_CREATION)) {

        userSignUpClient = retrofit.create(UserSignUpClient.class);
    } else if (baseUrlLink.equals(CONSTS.BASE_URL_ADDRESS_USER_INFO)){

        userInfoClient = retrofit.create(UserInfoClient.class);
    }
}

public UserSignInClient getUserSignInClient() {
    return userSignInClient;
}

public UserSignUpClient getUserSignUpClient() {
    return userSignUpClient;
}

public UserInfoClient getUserInfoClient() {
    return userInfoClient;
}
}

共有1个答案

司空凌
2023-03-14

以下为Android 6.0Marshmallow:

在清单中添加权限:

   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

对于Marshmallow及以上的设备:

    public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback{

  private static final int REQUEST_WRITE_PERMISSION = 786;

  @Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == REQUEST_WRITE_PERMISSION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {            
        openFilePicker();//do your job
    }
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    requestPermission();
  }

  private void requestPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
    } else {
        openFilePicker();//do your job
    }
  }
}
 类似资料:
  • 我有以下错误: 我为http请求设置了服务器,仍然得到错误:

  • 我正在使用翻新上传图像/文件 在这里,我发布了我的API调用以上传图像 请帮助我如何为这个调用编写接口,我已经用@part和@PartMap试过了,但是不起作用

  • 你好,我正在使用改型上传图像文件。有人知道怎么进去吗

  • http://letitripple.org/htmlform.html 这是此html表单创建的请求。(我从chrome开发者工具中获得) ------WebKitFormBoundaryPug6XAUALAUPBR86内容-配置:表单-数据;name=“wp-user-avatars”;filename=“desert.jpg”内容-类型:image/jpeg

  • 我要哭了,因为我尝试了很多解决方案和话题,但都不起作用。 null 您需要发送一个多部分请求(enctype=“multipart/form-data”)。 所以,有人能请帮助我,为什么我有HTTP 400与上面的错误消息?我可以在代码中更改什么以使此调用工作?谢谢你

  • 我有一个像下面的邮递员的形象。我如何在改型2中做同样的事情? 我这样声明接口: