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<Result> uploadImage(@Part MultipartBody.Part file);
}

三、添加權限

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

四、返回數據處理類

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<Result> call = service.uploadImage(body);
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> 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<Result> call, Throwable t) {
                Log.e("fail","fail");
            }
        });
    }
加上屬性:
private String path;

六、在服務器端的WWW目錄下新建一個php_upload,添加php文件

<?php
  
    $file_path = "";
     
    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        $result = array("result" => "success");
    } else{
        $result = array("result" => "error");
    }

    echo json_encode($result);

?>

七、調試

Android端:

服務端:

八、資料

使用Retrofit 2.0上傳圖片文件

九、源碼

GitHub:傳送


如果代碼有什麼錯誤大家可以提出來一起看看。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章