上传文件的步骤

public class MainActivity extends AppCompatActivity {
   private  MyRetrofitUtlis myRetrofitUtlis;
    private RecyclerView recyclerView;
    private Object resourseFile;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


    }

    public void onclick(View view) {

        Iview iview = MyRetrofitUtlis.getDefanult().create(Iview.class);
        File file= getResourseFile();

        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);

        MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);

        Call<UploadBaen> uploadBaenCall = iview.upLoadPhoto("71", part);



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

                UploadBaen body = response.body();

                String code = body.getCode();

                if (code.equals("0")){
                    Toast.makeText(MainActivity.this, "成功", Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(Call<UploadBaen> call, Throwable t) {

            }
        });


    }

    public File getResourseFile() {

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

        File file = new File(getCacheDir().getAbsolutePath());

        if (!file.exists()){

            file.mkdirs();
        }

        File file1 = new File(file,"photo.png");
        FileOutputStream fileOutputStream = null;


        try {
            fileOutputStream = new FileOutputStream(file1);
            bitmap.compress(Bitmap.CompressFormat.PNG,100,fileOutputStream);

            fileOutputStream.flush();

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

        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file1;
    }
}








《                                 Iview                               》 



@Multipart
@POST("file/upload")
Call<UploadBaen> upLoadPhoto(@Query("uid") String mobile, @Part MultipartBody.Part part);

猜你喜欢

转载自blog.csdn.net/zzf0521/article/details/80983784