繁体   English   中英

在 Android 中使用改造 2 上传二进制文件

[英]Upload binary file with retrofit 2 in Android

我想将二进制文件上传到 Android 中的服务器。 我通过邮递员测试了 Api 方法:

在此处输入图片说明

没关系,如您所见,还有另一个选项可以将文件作为表单数据(键,值)上传:

在此处输入图片说明

每个教程(如教程)都描述了如何将文件上传为multipart/form-data

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

    // MultipartBody.Part is used to send also the actual file name
    MultipartBody.Part body =
            MultipartBody.Part.createFormData("picture", file.getName(), requestFile);

我搜索了很多,但找不到任何方法使用retrofit2将文件上传为二进制文件。

改造存储库中只有一个问题,它询问如何在改造 2.0 测试版中发布图像二进制文件? . 我使用它的解决方案:

API服务:

@POST("trip/{tripId}/media/photos")
Call<MediaPost> postEventPhoto(
    @Path("eventId") int tripId,
    @Header("Authorization") String accessToken,
    @Query("direction") String direction,
    @Body RequestBody photo);

来电者:

InputStream in = new FileInputStream(new File(media.getPath()));
byte[] buf;
buf = new byte[in.available()];
while (in.read(buf) != -1);
RequestBody requestBody = RequestBody
    .create(MediaType.parse("application/octet-stream"), buf);
Call<MediaPost> mediaPostCall = tripApiService.postTripPhoto(
    tripId,
    ((GlobalInfo) getApplicationContext()).getApiAccessToken(),
    direction,
    requestBody);

但我收到了这个错误:

java.lang.IllegalArgumentException: @Body parameters cannot be used with form or multi-part encoding. 

我的代码有什么问题? 我该怎么办?

经过数小时的搜索,我发现在上一个示例中我的代码的 API 接口中保留了一个@Multipart注释! 防止将二进制数据发送到服务器,改造存储库中的解决方案是可以的!

只是添加另一个解决方案,因为我必须先深入了解一下问题中发生了什么。

我的解决方案是直接将二进制文件作为byte[] ,然后将其放入RequestBody 所以最后,代码看起来像这样:

interface RetrofitService {
    @POST("api/v1/upload_file")
    Call<Void> uploadBinaryFile(@Body RequestBody body);
}

并称之为:

public void uploadBinaryFile(File fileToUpload) {
    retrofitService
        .uploadBinaryFile(RequestBody.create(MediaType.parse("application/octet"), 
            Files.readAllBytes(fileToUpload));
}

这与 OP 的原始问题基本相同,但为了清楚起见,我也将这个答案留给下一位读者。

在 Kotlin 中,你可以这样做:

val file: File = retrieveMyJavaFile()
val requestBody: RequestBody = file.asRequestBody("application/octet-stream".toMediaTypeOrNull())
val response: MyResponse = myAPI.uploadPhoto(requestBody).body()!!

我有同样的问题,我想上传二进制文件(图像)。 API 是 Wordpress 的

我遵循了这个问题末尾给出的解决方案代码

这是我的小修改代码

@POST("wp-json/wp/v2/media/")
Call<ImagePostResult> postEventPhoto(
        @Header("Authorization") String accessToken,
        @Header("Content-Type") String contentType,
        @Header("Content-Disposition") String contentDisposition,
        @Body RequestBody photo);

这是请求

        // For BasicAuth
        String authHeader = getAuthHeader();

        String contentType = "application/binary";
        String contentDisposition = "attachment; filename =  " + fileName;

        RequestBody requestBodyee = null;
        try {
            InputStream in = new FileInputStream(file);

            byte[] buf;
            buf = new byte[in.available()];
            while (in.read(buf) != -1) ;
            requestBodyee = RequestBody
                    .create(MediaType.parse("application/octet-stream"), buf);
        } catch (IOException e) {
            e.printStackTrace();
        }


        Call<ImagePostResult> imagePostResultCall = apiInterface.postEventPhoto(
                authHeader,
                contentType,
                contentDisposition,
                requestBodyee);
        imagePostResultCall.enqueue(new Callback<ImagePostResult>() {
            @Override
            public void onResponse(Call<ImagePostResult> call, Response<ImagePostResult> response) {
                // Response Success
                if (response.isSuccessful()) {
                  // yaay
                }
            }

            @Override
            public void onFailure(Call<ImagePostResult> call, Throwable t) {
                Log.d(TAG, "onFailure: " + t);
            }
        });

您也可以将图像发送到

//Api Interface

@Part MultipartBody.Part body


//Call in activity
     file = FileUtils.getFile(this, uri);
                            reqFile = RequestBody.create(MediaType.parse("image/*"), file);
                            body = MultipartBody.Part.createFormData("uploaded_file", "Img_" + "_" + rightNow.getTimeInMillis() + ".jpg", reqFile);

只是 MediaType == Null 我的代码:

  private fun put(uploadUrl : String , localPath : String) {
        val file = File(localPath)
        val byteArray = file2Byte(localPath)!!
        val responseBody = RequestBody.create(null , byteArray)
        val call = HttpFactory.providerUp.up(uploadUrl , responseBody)

        call.enqueue(object : Callback<ResponseBody> {
            override fun onFailure(call : retrofit2.Call<ResponseBody>? , t : Throwable?) {
                LogUtil.toast("Failure")
            }

            override fun onResponse(call : retrofit2.Call<ResponseBody>? , response : retrofit.Response<ResponseBody>?) {
                if (response!!.code() == 200) {
                    LogUtil.toast("YES")
                } else {
                    LogUtil.toast("NO")
                }
            }
        })
    }
@PUT
    fun up2(@Url url : String ,@Body requestBody : RequestBody ) : Call<ResponseBody>

我像这样将图像上传到服务器,但在齐射中,这是我的代码希望这对某人有帮助

public void uploadImageToServer(byte[] value) {
        final StringRequest stringRequest = new StringRequest(Request.Method.PUT,uploadImageURL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e("s3 response", response);
                        Toast.makeText(context, "Image Uploaded to Server", Toast.LENGTH_LONG).show();
                       
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("error response", error.toString());
                        Toast.makeText(context, "Image Not Uploaded", Toast.LENGTH_LONG).show();
                    }
                }) {


            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headerMap = new HashMap<String, String>();
                headerMap.put("header1", "header value");
                headerMap.put("header2", "header value");
                headerMap.put("Content-Type", "image/jpeg");
                Log.e("header", headerMap.toString());
                return headerMap;
            }

            @Override
            public byte[] getBody() throws AuthFailureError {
                return value;
            }

        };
        {
            int socketTimeout = 30000;
            RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
            stringRequest.setRetryPolicy(policy);
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            requestQueue.getCache().clear();
            requestQueue.add(stringRequest);
        }
    }

如果任何 android 开发人员想在 volley 的帮助下使用二进制数据通过服务器上传文件。

public void uploadImageToServer (byte[] imageByte) {
            final StringRequest stringRequest = new StringRequest(Request.Method.POST,uploadImageURL,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Log.e("s3 response", response);
                            Toast.makeText(context, "Image Uploaded to Server", Toast.LENGTH_LONG).show();
                           
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.e("error response", error.toString());
                            Toast.makeText(context, "Image Not Uploaded", Toast.LENGTH_LONG).show();
                        }
                    }) {
    
    
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> headerMap = new HashMap<String, String>();
                    headerMap.put("header1", "header value");
                    headerMap.put("Content-Type", "image/jpeg");
                    return headerMap;
                }
    
                @Override
                public byte[] getBody() throws AuthFailureError {
               //Binary value data
                    return value;
                }
    
            };
            {
                int socketTimeout = 30000;
                RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
                stringRequest.setRetryPolicy(policy);
                RequestQueue requestQueue = Volley.newRequestQueue(this);
                requestQueue.getCache().clear();
                requestQueue.add(stringRequest);
            }
        }



 
//You can convert any file to byte array
 public static byte[] convertFileToBytes(File file)
    {
     int size = (int) userImageFile.length();
        byte[] bytes = new byte[size];
        try {
            BufferedInputStream buf = new BufferedInputStream(new FileInputStream(userImageFile));
            buf.read(bytes, 0, bytes.length);
            buf.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return bytes;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM