无法在Android

时间:2016-10-12 14:04:29

标签: android file-upload retrofit multipartform-data retrofit2

我正在开发一个Android应用程序。在我的应用程序中,我需要在multipart / form-data请求中将多个或一组文件上传到服务器。我正在使用Retrofit 2。我可以将单个文件上传到服务器。但是当我上传文件列表时,服务器端的文件值始终为空。

这是我的改装服务界面

public interface ApiService {

    @Multipart
    @POST("Troll/CreateMemePost")
    Call<ResponseBody> postMeme(@Part List<MultipartBody.Part> files, @Part("AuthToken") RequestBody authToken);
}

如您所见,我正在尝试上传文件列表作为第一个参数。

这是我在活动中上传的方式

final ArrayList<File> photoFiles = new ArrayList<File>();
        ArrayList<MultipartBody.Part> files = new ArrayList<MultipartBody.Part>();
        for(Bitmap bitmap: previewBitmaps)
        {
            File file = null;
            try{
                String fileName = String.valueOf(System.currentTimeMillis())+".jpeg";
                file = new File(Environment.getExternalStorageDirectory(), fileName);
                if(file.exists())
                {
                    file.delete();
                }
                OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
                os.close();
                photoFiles.add(file);
                RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"),file);
                MultipartBody.Part partFile = MultipartBody.Part.createFormData("multipart/form-data",file.getName(),requestFile);
                files.add(partFile);
            }
            catch (Exception e)
            {
                Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
            }
        }

        if(files!=null && files.size()>0)
        {
            final Retrofit retrofit = app.getApiClient().getRetrofit();
            ApiService service = app.getApiClient().getApiService();

            RequestBody authToken = RequestBody.create(MediaType.parse("multipart/form-data"), app.getAuthToken());

            Call<ResponseBody> call = service.postMeme(files,authToken);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if(photoFiles!=null && photoFiles.size()>0)
                    {
                        for(File tempFile : photoFiles)
                        {
                            if(tempFile.exists())
                            {
                                tempFile.delete();
                            }
                        }
                    }
                    if(response!=null)
                    {
                        if(response.isSuccessful())
                        {
                            Toast.makeText(getBaseContext(),"File Uploaded successfully",Toast.LENGTH_SHORT).show();
                        }
                        else if(!response.isSuccessful() && response.errorBody()!=null)
                        {
                            Toast.makeText(getBaseContext(),"Server error message",Toast.LENGTH_SHORT).show();
                            /*try{

                            }
                            catch (IOException e)
                            {
                                Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                            }*/
                        }
                    }
                    else{
                        Toast.makeText(getBaseContext(),"Response is null",Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    if(photoFiles!=null && photoFiles.size()>0)
                    {
                        for(File tempFile : photoFiles)
                        {
                            if(tempFile.exists())
                            {
                                tempFile.delete();
                            }
                        }
                    }
                    Toast.makeText(getBaseContext(),"Unable to transfer data to server",Toast.LENGTH_SHORT).show();
                }
            });
        }

但是当我上传时,我在服务器端成功收到了AuthToken字段。但文件值始终为null。我正在使用ASP.NET MVC作为后端。您可以在下面看到截图。它始终为空。你在服务器端就像这样绑定。

public JsonResult CreateMemePost(IEnumerable<HttpPostedFileBase> files,CreateMemePostModel model)

文件始终为null,模型中的AuthToken字段显示为从我的应用程序发送。当我像这样上传单个文件时

public JsonResult CreateMemePost(HttpPostedFileBase file,CreateMemePostModel model)

正在运行并成功上传。我很确定问题出在我的改造代码上。我的代码出了什么问题?如何使用Android中的改造在multipart / form-data请求中将文件列表上传到服务器?

我也试过这个,只上传文件

public interface ApiService {

    @FormUrlEncoded
    @POST("Troll/CreateMemePost")
    Call<ResponseBody> postMeme(@Field("files") ArrayList<RequestBody> files);//, @Part("AuthToken") RequestBody authToken);
}

服务器端的文件计数始终为0。

然后我尝试了另一种使用MapPart的解决方案

public interface ApiService {
    @Multipart
    @POST("Troll/CreateMemePost")
    Call<ResponseBody> postMeme(@PartMap() Map<String,RequestBody> files, @Part("AuthToken") RequestBody authToken);
}

我在活动中创建这样的地图

 HashMap<String,RequestBody> map = new HashMap<>();
 // Other steps
 MediaType MEDIA_TYPE=MediaType.parse("multipart/form-data");
 bodyFile = RequestBody.create(MEDIA_TYPE,file);
 map.put("files",bodyFile);

服务器上的文件始终为空。

1 个答案:

答案 0 :(得分:1)

最后,我找到了解决方案。我使用了RequestBody和MultipartBody.Builder。我在Github上传了解决方案。

请查看此链接 - https://github.com/waiyanhein/how-to-upload-multiple-files-using-retrofit-in-android