Android上传图片到PHP服务端 |
您所在的位置:网站首页 › 安卓php服务器palapa › Android上传图片到PHP服务端 |
在
上一期Android博客中利用Takephoto开源库获取并裁剪图片,代码很精简,在这个基础上我们获取到图片一般都是要
进行上传等操作,那我们就开始吧。 上一期传送门 上传方式是通过retrofit2.0的库。 一、集成retrofit compile 'com.squareup.retrofit2:retrofit:2.2.0' compile 'com.squareup.okhttp3:okhttp:3.6.0' compile 'com.squareup.retrofit2:converter-gson:2.2.0' 二、Service public interface ApiService { @Multipart @POST("upload.php") Call uploadImage(@Part MultipartBody.Part file); } 三、添加权限 四、返回数据处理类 public class Result { @SerializedName("result") @Expose private String result; /** * @return The result */ public String getResult() { return result; } /** * @param result The result */ public void setResult(String result) { this.result = result; } } 五、上传(在上次程序中的takeSuccess方法中对获取到的图片提取路径并上传) @Override public void takeSuccess(TResult result) { super.takeSuccess(result); // Log.e("success",""+result.getImage().getOriginalPath().toString()); //成功后将图片地址和图片显示到控件上 tv.setText(result.getImage().getOriginalPath().toString()); path=result.getImage().getOriginalPath().toString(); Glide.with(this).load(new File(result.getImage().getOriginalPath())).into(img); Retrofit retrofit= new Retrofit.Builder() .baseUrl("http://39.105.20.169/php_upload/") .addConverterFactory(GsonConverterFactory.create()) .build(); ApiService service = retrofit.create(ApiService.class); File file = new File(path);//访问手机端的文件资源,保证手机端sdcdrd中必须有这个文件 if(!file.exists()){ Log.e("fail","not exist"); return; } RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); MultipartBody.Part body = MultipartBody.Part.createFormData("uploaded_file", file.getName(), requestFile); Call call = service.uploadImage(body); call.enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { if (response.isSuccessful()) { if (response.body().getResult().equals("success")) Log.e("success","success"); Toast.makeText(TestActivity.this,"上传成功",Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call call, Throwable t) { Log.e("fail","fail"); } }); }加上属性: private String path; 六、在服务器端的WWW目录下新建一个php_upload,添加php文件Android端: 服务端: 使用Retrofit 2.0上传图片文件 九、源码GitHub:传送 如果代码有什么错误大家可以提出来一起看看。 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |