爲啥用okhttp?
安卓app請求都用的okhttp,懶得再搞別的開源項目
我這篇文章主要是解決上傳的問題的,先說一下,我是修改於這篇文章
https://blog.csdn.net/chaoyu168/article/details/77880320
我主要說一下上傳方面吧
我使用本代碼有個小問題,發現獲取文件目錄的時候,返回的參數是空,emmmm,先設置參數爲固定的
//點擊按鈕開始上傳文件
public void startUploadClick() {
//tempFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "test1.txt");
//showFileChooser();
String fileName = "";
//File tempFile = new File(textView.getText().toString());
tempFile = new File("/storage/emulated/0/Android/MavBox/test/logo.jpg");
if (tempFile.getName() == null){
Toast.makeText(MainActivity.this, "找不到該文件!", Toast.LENGTH_SHORT).show();
}
else {
fileName = getFileName("/storage/emulated/0/Android/MavBox/test/logo.jpg");
}
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", fileName, RequestBody.create(MediaType.parse("image/jpg"), tempFile))
.build();
//ProgressRequestBody progressRequestBody = new ProgressRequestBody(requestBody, progressListener);
Request request = new Request.Builder()
.url("http://www.shuchuwenku.vip/MavBox/updatefile/receive_file.php")
.post(requestBody)
.build();
//上面url中的內容請改成自己php文件的所在地址
okHttpClient.newCall(request).enqueue(callback_upload);
}
/storage/emulated/0/Android/MavBox/test/logo.jpg
是我手機裏面的文件路徑,文件已經存在,
選擇器獲取的文件路徑有問題,估計要重新寫一個
服務器代碼沒問題,其他沒有的話,我這邊粘貼一下
<?php
$base_path = "./uploads/"; //存放目錄
if(!is_dir($base_path)){
mkdir($base_path,0777,true);
}
$target_path = $base_path . basename ( $_FILES ['file'] ['name'] );
if (move_uploaded_file ( $_FILES ['file'] ['tmp_name'], $target_path )) {
$array = array (
"status" => true,
"msg" => $_FILES ['file'] ['name']
);
echo json_encode ( $array );
} else {
$array = array (
"status" => false,
"msg" => "There was an error uploading the file, please try again!" . $_FILES ['file'] ['error']
);
echo json_encode ( $array );
}
?>
後面有需求我再完善,也是不注意,研究了好一會兒都沒發現選擇後返回路徑有問題