使用改造将图像上传到服务器

时间:2018-04-25 07:08:11

标签: android request retrofit2

我想使用下面的代码

使用其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也可以。我是新来的,所以有人会发现我的错误,并详细解释为什么这是错误的。

2 个答案:

答案 0 :(得分:0)

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

    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;
        }
    }

答案 1 :(得分:0)

如果有人发现它有用,那么错误是在第一个参数“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());
                    }

所以,改变它并删除所有不必要的东西就足够了。 当然,还需要根据参数更改服务文件。我没有注意它,因为在教程中它没有被提及作为一些重要的参数。

相关问题