如何使用Retrofit2上传图像并将其保存在NodeJS服务器上?

时间:2016-08-07 23:53:33

标签: android node.js post retrofit

我有Android应用程序使用Retrofit2将图像发布到NodeJS服务器。 这是我的Android / Java代码:

public interface ApiInterface {
    String ENDPOINT = "http://192.168.0.11:1337/";

    @Multipart
    @POST("users/avatar")
    Call<Avatar> postAvatar(@Part("description") RequestBody description, @Part("image") MultipartBody.Part file);

    public static final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(ENDPOINT)
            .addConverterFactory(GsonConverterFactory.create())
           .build();
}

private void uploadAvatar(final String userid){
     File file = new File("/storage/emulated/0/Android/data/com.bcg.loginexample/files/pic.jpg");

        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body =MultipartBody.Part.createFormData("image", file.getName(), requestFile);
        String descriptionString = "hello, this is description speaking";
        RequestBody description =RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString);

        ApiInterface mApiService = ApiInterface.retrofit.create(ApiInterface.class);
        Call<Avatar> mService=  mApiService.postAvatar(description, body );
        mService.enqueue(new Callback<Avatar>() {
            @Override
            public void onResponse(Call<Avatar> call, Response<Avatar> response) {
                Avatar avatar = response.body();
                String returnedResponse = avatar.avatar_url;
                Toast.makeText(LoginActivity.this, "Returned " + returnedResponse, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(Call<Avatar> call, Throwable t) {
                call.cancel();
                Toast.makeText(LoginActivity.this, "Please check your network connection", Toast.LENGTH_LONG).show();
            }
        });
    }

和NodeJS

app.post('/users/avatar', type,
  function (req, res) {
     var filePath = __dirname + '/uploads/avatar.jpg';
     fs.appendFile(filePath, req.body.image, function () {
       res.end('file uploaded');
     });
  });

这就是我在NodeJS端的body对象中看到的全部内容。

"{"headers":{"namesAndValues":["Content-Disposition","form-data; name=\"image\"; filename=\"pic.jpg\""]}}"

不知道这里的图像在哪里以及如何保存它?

1 个答案:

答案 0 :(得分:0)

您需要一些额外的中间件来处理多部分/表单数据(上传二进制数据)。例如,您可以查看multer模块。