2017-01-28 3 views
0

내 응용 프로그램에서 비디오 파일을 업로드하려고합니다.retrofit2 업로드 파일

는 여기에 지금까지있어 무엇 :

public class Download extends Application { 

public interface upload { 
    @Multipart 
    @POST("new") 
    Call<Response> send(@Part("myFile") RequestBody file); 
} 

public void uploadFile(File xfile) { 

    Retrofit retrofit = new Retrofit.Builder() 
      .baseUrl("http://192.168.0.3") 
      .addConverterFactory(GsonConverterFactory.create()) 
      .build(); 

    RequestBody file = RequestBody.create(MediaType.parse("video/*"), xfile); 
    upload xUpload = retrofit.create(upload.class); 
    Call<Response> call = xUpload.send(file); 

    try { 
     Response result = call.execute().body(); 


    } 
    catch (IOException e) 
    { 
     Log.d("TEST3", " didn't work "); 
    } 

} 




} 

나는 다음과 같은 오류 retrofit2.Response를 얻을 '유효한 응답 본문의 형식이 아닙니다. ResponseBody를 의미 했습니까? 방법 upload.send에 대한 아이디어가

나는 retrofit2 웹 페이지를 읽고 파일 업로드에 대한 주요 예제를 시도했지만 두 가지 이유로 작동하지 않습니다. 1. ServiceGenerator를 찾을 수 없습니다. 2. 내 파일을 갤러리에서 찾았습니다. 업로드 할 임시 파일에 내용을 스트리밍했습니다. URI에서 직접 액세스 할 수 없습니다 ... 또는 retrofit2로 할 수 있을까요?

+1

https : // futur estud.io/tutorials/retrofit-2-how-to-upload-files-to-server – AnixPasBesoin

+0

최근에이 튜토리얼을 따라 파일 업로드를 완료했습니다 https://futurestud.io/tutorials/retrofit-2-passing-multiple -parts-along-a-file-with-partmap – rajesh

답변

0

내가 이런 개조 2에서 이미지를 업로드하는 데 사용하는, 그것은

File file = new File(image.getPath()); 
      RequestBody mFile = RequestBody.create(MediaType.parse("image/*"), file); 
      MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("gallery", file.getName(), mFile); 
      RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), id); 
      final NetworkCall networkCall=new NetworkCall(this); 
      Call<ResponseBody> call = networkCall.getRetrofit(false).uploadImage(filename, fileToUpload); 
      call.clone().enqueue(new Callback<ResponseBody>() { 
       @Override 
       public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 

       } 

       @Override 
       public void onFailure(Call<ResponseBody> call, Throwable t) { 

       } 
      }); 
여기

내 네트워크 호출 클래스입니다 제대로 일 :

public class NetworkCall { 
    Context context; 
    ProgressDialog progressDialog; 
    public NetworkCall(Context context){ 
     this.context = context; 
    } 

    public IApi getRetrofit(boolean isShowLoading){ 

     OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); 
     httpClient.connectTimeout(0, TimeUnit.SECONDS).readTimeout(0,TimeUnit.SECONDS); 

     httpClient.addInterceptor(new Interceptor() { 
             @Override 
             public Response intercept(Chain chain) throws IOException { 
              Request original = chain.request(); 

              Request request = original.newBuilder() 
                .header("Content_type","application/json") 
                .header("Accept", "application/json") 
                .method(original.method(), original.body()) 
                .build(); 

              return chain.proceed(request); 
             } 
            }); 
     Gson gson = new GsonBuilder() 
       .setLenient() 
       .create(); 

       OkHttpClient client = httpClient.build(); 
     Retrofit retrofit = new Retrofit.Builder() 
       .baseUrl(Constants.BASE_URL) 
       .client(client) 
       .addConverterFactory(GsonConverterFactory.create(gson)) 
       .build(); 
     if (isShowLoading&&context instanceof BaseActivity) 
      showLoading(); 
     // prepare call in Retrofit 2.0 

     IApi api = retrofit.create(IApi.class); 
//  Call<BaseResponce> call = api.callService(json); 
     //asynchronous call 
//  call.enqueue(this); 
     return api; 
    } 
    private void showLoading(){ 
     try { 
      ((BaseActivity)context).runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        progressDialog = new ProgressDialog(context); 
        progressDialog.setMessage("Please wait..."); 
        progressDialog.setCancelable(false); 
        progressDialog.show(); 
       } 
      }); 

     }catch (Exception e){ 
      e.printStackTrace(); 
     } 
    } 

    public void dismissLoading(){ 
     try { 
      ((BaseActivity)context).runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        progressDialog.cancel(); 
        progressDialog.dismiss(); 
       } 
      }); 

     }catch (Exception e){ 
      e.printStackTrace(); 
     } 
    } 
} 

내가 IApi 클래스에서 이것을 사용

@Multipart 
    @POST("events/file_upload.json") 
    Call <ResponseBody> uploadImage(@Part("event_id") RequestBody id,@Part MultipartBody.Part part); 

도움이 되겠습니다.

관련 문제