android - 如何使用 Retrofit2 将照片上传到服务器

标签 android performance http upload retrofit

有谁知道使用改造 2 将图像上传到服务器的方法。大多数在线解决方案都使用改造 1。

谢谢 我试过这个:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    //GALLERY
    if ((isGalleryCalled(requestCode) && resultCode == RESULT_OK)) {
        Log.w(TAG, "onActivityResult > isGalleryCalled > data.getData(): " + data.getData());
        Uri originalUri = data.getData();
        if (originalUri != null) {
            mImageUri = originalUri;
        }
    }
    //CAPTURE
    else if ((isCaptureCalled(requestCode)) && resultCode == RESULT_OK) {
        Log.w(TAG, "onActivityResult > isCaptureCalled > data.getData(): " + data.getData());
        Uri originalUri = data.getData();
        if (originalUri != null) {
            mImageUri = originalUri;

        }
    }



private void prepareImage(String mImageUri ) {

    File file = new File(mImageUri );

    mRequestBodyImage =  RequestBody.create(MediaType.parse("multipart/form-data"), file);

    isUploadImage = true;
    Log.d(TAG, "isUploadImage: " + isUploadImage + " | \nuri: " + uri + " | \nfile getPath: " + file.getPath());

}//end sendReport




    Call<DefaultResponse> call = RestClient.get().uploadImage(file);

....


    @Multipart
    @POST(Constant.API_UPLOADIMAGE)
    Call<DefaultResponse> uploadImage(
            //Upload File
            @Part("myfile\"; filename=\"image.png\" ") RequestBody file
    ); 

我收到这些错误:

sendErrorReport - file: com.squareup.okhttp.RequestBody$3@2f83a2f9
stat failed: ENOENT (No such file or directory) : content:/media/external/images/media/2720
java.io.FileNotFoundException: content:/media/external/images/media/2720: open failed: ENOENT (No such file or directory)
at libcore.io.IoBridge.open(IoBridge.java:456)
at java.io.FileInputStream.<init>(FileInputStream.java:76)
at okio.Okio.source(Okio.java:163)
at com.squareup.okhttp.RequestBody$3.writeTo(RequestBody.java:117)
at com.squareup.okhttp.MultipartBuilder$MultipartRequestBody.writeOrCountBytes(MultipartBuilder.java:277)
at com.squareup.okhttp.MultipartBuilder$MultipartRequestBody.writeTo(MultipartBuilder.java:297)

[更新]

Update code from feed back from @Anton Shkurenko

图像路径开始处理

UtilApiHelp.getPath:/storage/emulated/0/DCIM/Camera/20151210_124246.jpg

private void prepareImage(String uri) {


    File file = new File(uri);

    mRequestBodyImage =  RequestBody.create(MediaType.parse("multipart/form-data"), file);

    isUploadImage = true;
    Log.d(TAG, "prepareImage isUploadImage: " + isUploadImage + " | \nuri: " + uri + " | \nfile getPath: " + file.getPath());


    sendErrorReport("", mRequestBodyImage);// test1
uploadImage(file.getPath());//test 2
}//end sendReport



//API Send Image test 1 - FAILED
private void sendErrorReport(String s, String msg, RequestBody file){

    Log.e(TAG, "sendErrorReport - file: " + file.toString());

    String user_id = Preferences.getInstance().getUserId();

    Call<DefaultResponse> call = RestClient.get().sendErrorReport(s, file);
    call.enqueue(new Callback<DefaultResponse>() {
        @Override
        public void onResponse(Response<DefaultResponse> response, Retrofit retrofit) {

            Log.w("sendErrorLog > onResponse => ", String.valueOf(response.isSuccess()));

        }

        @Override
        public void onFailure(Throwable t) {
            t.printStackTrace();
        }
    });
}

error: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 3 column 2 path $

//Upload test 2 -> not working
private void uploadImage(final String path) {


    final RequestBody photo =
            UtilApiHelp.getImageBodyBuilder(new HashMap<String, String>() {{
                put("image", path);
            }})
                    //.addFormDataPart("here_you_can_add_another_form_data", anotherFormData)
                    .build();


    Call<DefaultResponse> call = RestClient.get().sendErrorReport(photo);
    call.enqueue(new Callback<DefaultResponse>() {
        @Override
        public void onResponse(Response<DefaultResponse> response, Retrofit retrofit) {

        }

        @Override
        public void onFailure(Throwable t) {
            t.printStackTrace();
        }
    });
}

Error: Caused by: java.lang.IllegalArgumentException: @Body parameters cannot be used with form or multi-part encoding. (parameter #1) for method APIService.sendErrorReport

使用了这个电话

@FormUrlEncoded
@POST(Constant.API_POST_error_log)
Call<DefaultResponse> sendErrorReport(@Body RequestBody multipartBody);

最佳答案

[更新]
由于您更新了问题。您只是无法从给定的 Uri 中找到文件。使用我的代码中的 util 函数 getPath 获取图像路径,希望这会起作用。

[旧解决方案]
我有这个可行的解决方案:

实用函数:

public static RequestBody getImageBody(Map<String, String> map) {
  return getImageBodyBuilder(map).build();
}

public static MultipartBuilder getImageBodyBuilder(Map<String, String> map) {

  MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);
  for (String key : map.keySet()) {
    final String filePlace = map.get(key);
    Log.d(TAG, "File place: " + filePlace);
    final String[] args = filePlace.split("\\.");
    final String fileExt = args[args.length - 1];
    Log.d(TAG, "File extension: " + fileExt);

    // Old solution, porting from one project to another
    // It's about problems with jpeg
    builder.addPart(Headers.of("Content-Disposition",
        "form-data; name=\"" + key + "\"; filename=\"" + filePlace + "\""), RequestBody.create(
        MediaType.parse("image/" + fileExt.toLowerCase().replace("jpg", "jpeg")),
        new File(map.get(key))));
  }

  return builder;
}

public static String getPath(Context ctx, Uri uri) {
  String[] projection = { MediaStore.Images.Media.DATA };
  Cursor cursor = ctx.getContentResolver().query(uri, projection, null, null, null);
  if (cursor == null) return null;
  int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  cursor.moveToFirst();
  String s = cursor.getString(columnIndex);
  cursor.close();
  return s;
}

照片上传。

final RequestBody photo =
    ImageUploadUtils.getImageBodyBuilder(new HashMap<String, String>() {{
                put("photo", imagePathWhateverYouWant);
              }})
              .addFormDataPart("here_you_can_add_another_form_data", anotherFormData).build();

 mApiService.attachPhoto("Token " + getToken(), photo);

ApiService.java(接口(interface)):

// I user here RxJava, but I think it's easy to use Calls here.
@POST("deliveries/photos") Observable<Map<String, String>> attachPhoto(
     @Header("Authorization") String token, 
     @Body RequestBody multipartBody);

关于android - 如何使用 Retrofit2 将照片上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34175313/

相关文章:

sql - 为什么 SQLite 需要这么长时间来获取数据?

http - 在 nginx 中将所有 http 重定向到 https,除了一个文件

http - http ://example. com 和 http ://www. example.com 之间的区别

java - Android代码转纯java

android - 单击时键盘与 EditText 重叠

java - 抛出异常的哪一部分是昂贵的?

c++ - 使用套接字发送文件

android - 自定义 Android 下载服务 - 为每个文件提供进度通知行

android - Git 存储库突然不再更新,即使它在 Android Studio 端提交/推送正常

c - C 中每 N 个元素中出现次数最多的元素