【问题标题】:Upload image into server using retrofit使用改造将图像上传到服务器
【发布时间】:2018-10-05 13:33:46
【问题描述】:

我想使用下面的代码使用其 uri 将图像/文件上传到服务器

try {

                    String descriptionString = "Sample description";
                    RequestBody description = RequestBody.create(MultipartBody.FORM, descriptionString);

                    File file = new File(path);

                    String extension = MimeTypeMap.getFileExtensionFromUrl(uri.toString());

                    if (extension != null) {

                        String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                        RequestBody requestFile = RequestBody.create(MediaType.parse(type), file);

                        MultipartBody.Part body2 = MultipartBody.Part.createFormData("avatar", file.getName(), new FileRequestBody(file, extension));

                        Response<ResponseBody> response = ApiCaller.getProfileAPI().requestingUploadProfilePhoto("Bearer " + AuthenticationProvider.getInstance().token.token,
                                "form-data; name=avatar; filename=\"" + file.getName() + "\"",
                                ProfileProvider.getInstance().parsedProfile.profileId,
                                description,
                                body2).execute();
                        if (response.isSuccessful()){
                            Logger.msg("Photo", ": uploaded successfully " + uri);
                        }else{
                            Logger.msg("Photo", ": uploaded successfully none" + uri + response.errorBody().string());
                        }
                    }else{
                        Logger.msg("Photo", ":extension error");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

我对该请求的 API 服务

 @Multipart
@POST("v1/avatar/profiles/{profileId}/upload")
Call<ResponseBody> requestingUploadProfilePhoto(@Header("Authorization") String authHeader,
                                                @Header("Content-Disposition") String content_type,
                                                @Path("profileId") String profileId,
                                                @Part("description") RequestBody description,
                                                @Part MultipartBody.Part file);

所以,这里我的回复不成功。 API 返回内部服务器错误状态 500,但我知道服务器运行良好(我测试了其他应用程序)。另外,文件uri也可以。我是新来的,所以有人能找到我的错误并详细解释为什么会出错。

【问题讨论】:

    标签: android request retrofit2


    【解决方案1】:

    如果有人觉得它有用,这里的第一个参数“name”是错误的(在我的情况下,根据服务器,它应该是“file”,而不是“avatar”)

    MultipartBody.Part body2 = MultipartBody.Part.createFormData("avatar", file.getName(), new FileRequestBody(file, extension));
    
    Response<ResponseBody> response = ApiCaller.getProfileAPI().requestingUploadProfilePhoto("Bearer " + AuthenticationProvider.getInstance().token.token,
                                ProfileProvider.getInstance().parsedProfile.profileId,
                                body2).execute();
                        if (response.isSuccessful()){
                            Logger.msg("Photo", ": uploaded successfully " + uri);
                        }else{
                            Logger.msg("Photo", ": uploaded successfully none" + uri + response.errorBody().string());
                        }
    

    所以,改变它并删除所有不必要的东西就足够了。 当然,也有必要根据参数更改服务文件。我没有引起足够的重视,因为在教程中没有提到它是一些重要的参数。

    【讨论】:

      【解决方案2】:

      您可以使用将图像转换为文件并创建一个多部分请求,如下所示

          String fileName = "myFile";
          RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
          MultipartBody.Part body = MultipartBody.Part.createFormData("image", fileName, reqFile);
      

      要将图像转换为文件,请使用以下函数

          public static File convertBitmapToFile(Context mContext, Bitmap bitmap) {
              try {
                  File f = new File(mContext.getCacheDir(), "image");
                  f.createNewFile();
      
                  ByteArrayOutputStream bos = new ByteArrayOutputStream();
                  bitmap.compress(Bitmap.CompressFormat.JPEG, 60 /*ignored for PNG*/, bos);
                  byte[] bitmapdata = bos.toByteArray();
      
      
                  FileOutputStream fos = new FileOutputStream(f);
                  fos.write(bitmapdata);
                  fos.flush();
                  fos.close();
                  return compressImageFile(mContext, f);
              } catch (IOException e) {
                  e.printStackTrace();
                  return null;
              }
          }
      

      改造 API 定义

          @Multipart
          @POST("/upload/image")
          Call<ResponseBody> uploadImage(@Part MultipartBody.Part image);
      

      压缩器功能使用下面的代码

      在 gradle 中添加这个

      compile 'id.zelory:compressor:2.1.0'
      
      
      
      public static File compressImageFile(Context mContext, File file) {
              try {
                  return new Compressor(mContext).compressToFile(file);
              } catch (IOException e) {
                  e.printStackTrace();
                  return file;
              }
          }
      

      【讨论】:

      • 为什么要把它转换成文件?此外,当我检查图像的类型时,它是文件。
      • 如果您将其转换为文件,如上例所示,它将上传到服务器,并且可以在 android 中访问以显示在 ImageView 中
      • 好的,我会试试,但是你能告诉我方法 compressImageFile 在哪里吗?
      • 不幸的是,它没有帮助。
      • 您遇到了什么错误?如果它的 500 内部服务器错误。您可能想检查您的服务器日志。
      猜你喜欢
      • 1970-01-01
      • 2019-02-14
      • 2017-05-21
      • 2021-09-01
      • 2018-01-23
      • 2018-02-19
      • 2018-04-03
      • 2018-10-10
      • 2021-10-10
      相关资源
      最近更新 更多