为啥用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 );
}
?>
后面有需求我再完善,也是不注意,研究了好一会儿都没发现选择后返回路径有问题