简体   繁体   中英

How to upload Image to server from android retrofit

Still looking for solution. Anyone know how to do this

I am uploading image from mobile to service. I uploaded image successfully but dont know how to save

I am using compile 'com.squareup.retrofit2:retrofit:2.1.0'

retrofit method

@Multipart
@POST("RestService/json/PostKYCDocImg/")
Call<UploadPictureResponse> getURLKYCDocImg(@Part MultipartBody.Part imageData);

in android uploaded file by

File file = new File(new URI(de.getAttachFilePath()).getPath());
RequestBody mFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part image = MultipartBody.Part.createFormData("image", file.getName(), mFile);
Call<UploadPictureResponse> call = apiService.getURLKYCDocImg(image);

In Wcf webservice i am receiving by

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/json/PostKYCDocImg/", RequestFormat = WebMessageFormat.Json, 
ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
[FaultContract(typeof(ServiceData))]
string UploadPicture(Stream imageData);


public string UploadPicture(Stream imageData)         
{   
   //saveImgInSpecPath(fileFullPath, GetBytesFromStream(imageData, 
   //System.Text.Encoding.UTF8), imageData); 

   saveImgInSpecPath2(fileFullPath, imageData);
}

private static Boolean saveImgInSpecPath2(string fileFullPath, Stream imageData)
{
   try
   { 
       //Save image here which is in imageData as stream and return saved status
       //var fileStream = File.Create(fileFullPath);
       //imageData.CopyTo(fileStream);

        //StreamReader sr = new StreamReader(imageData.InputStream);
        //var fileStream = File.Create(fileFullPath);
        //imageData.InputStream.Seek(0, SeekOrigin.Begin);
        //imageData.InputStream.CopyTo(fileStream);  

        //here i want to save image file which imageData in the form of stream

       bool exists = File.Exists(fileFullPath);
       return exists;
    }
   catch (Exception ex)
    {
           return false;
    }
}

I tried lot of code in "saveImgInSpecPath2" method, all codes are uploaded to service path successfully but saved wrongly

please suggest right way to save in wcf webservice from android retrofit

I've used this in my project. And it works correctly.

Stream str = File.OpenRead(@"C:\Users\a.asadi\Pictures\Capture.PNG");
FileStream fs = File.Create(@"C:\Users\a.asadi\Pictures\test.PNG", (int)str.Length);
byte[] bytes = new byte[str.Length];
str.Read(bytes, 0, bytes.Length);
fs.Write(bytes, 0, bytes.Length);
// retrofit method APIgetpost(interface java class)


 @Multipart
   @POST("RestService/json/PostKYCDocImg/")
   Call<UploadPictureResponse> getURLKYCDocImg(@Part@Part MultipartBody.Part 
   file1);

//java class:

public void ProfileupdateExecute() {
  ApiGetPost service = ApiConstant.getMainUrl().create(ApiGetPost.class);

      JSONObject jTestObj = new JSONObject();
      if (mediaPath != null) {
          strImgaepath = mediaPath;
      } else {
          strImgaepath = "";
      }

      //File creating from selected URL
      File file = new File(strImgaepath);

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

      userimage =
                MultipartBody.Part.createFormData("photo", file.getName(), requestFile);


       try {
       //photo field name

       jTestObj.put("photo", strImgaepath);

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

       updatecall = service.ProfileUpdate(userimage);


    updatecall.enqueue(new Callback<UpdateTeacherProfileModel>() {
            @Override
            public void onResponse(Call<UpdateTeacherProfileModel> call, Response<UpdateTeacherProfileModel> response) {

                viewDialog.hideDialog();

                if (response.body()!= null) {

                    UpdateTeacherProfileModel userupdate = (response.body());
                    String Success = userupdate.getSuccess();

                    if (Success.equalsIgnoreCase("true")){
                        Toast.makeText(ProfileView_Activity.this, "Success", Toast.LENGTH_SHORT).show();

                    } else {
                        Toast.makeText(ProfileView_Activity.this, "Check your credentials", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "Error..!", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<UpdateTeacherProfileModel> call, Throwable t) {
                viewDialog.hideDialog();
                Toast.makeText(getApplicationContext(), "Please try again", Toast.LENGTH_SHORT).show();
                call.cancel();
            }
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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