1.php代码
<?php
//申请人预约信息提交
$link = mysqli_connect('localhost', 'root', '******', 'datedemo');
//分为两种状态,链接数据库失败,封装json发送给Android端
if(!$link){
$response = array();
$response["success"] = 3;
//输出给前端
echo json_encode($response);
}else {
//接受post的key
$name = $_POST['name'];
if(empty($_FILES)) die('{"status":0,"msg":"错误提交"}');
$dirPath = './img/';//设置文件保存的目录
if(!is_dir($dirPath)){
//目录不存在则创建目录
@mkdir($dirPath,777);//文件权限,若不设置为可读可写则无法将上传的图片复制到img文件夹下
}
if($_FILES["file"]["error"]) //file是input上传图片时候的name
{
$arr['msg']= $_FILES["file"]["error"];
}
$count = count($_FILES);//所有文件数
if($count<1) die('{"status":0,"msg":"错误提交"}');//没有提交的文件
$success = $failure = 0;
foreach($_FILES as $key => $value){
//循环遍历数据
$tmp =$value['name'];//获取上传文件名
$tmpName = $value['tmp_name'];//临时文件路径
//上传的文件会被保存到php临时目录,调用函数将文件复制到指定目录
$filename="img/" .$tmp;
if(move_uploaded_file($tmpName,$filename)){
$sql = "insert into show_yuyue (name,imgurl) values('$name','$filename')";
//建立链接
$result = mysqli_query($link, $sql);
if ($result) {
//添加注册成功的标志
$response["success"] = 1;
} else {
$response["success"] = 0;
}
}}
echo json_encode($response);
mysqli_close($link);
//关闭数据库
}
?>
2.Android端(只贴出来了关键代码)
利用的是OKhttp来上传图片,使用OKhttp摸仪器API>=20
//从相册中获取图片
public void loadImage() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
//当图片被选中的返回结果
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// 获取游标
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
imageView.setImageBitmap(BitmapFactory.decodeFile(imgPath));
Log.i("TAG_----->path",imgPath);
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
}
//上传图片
private void postImage() {
File file = new File(imgPath);
Bitmap bm = BitmapFactory.decodeFile(imgPath);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("name", "hehe")
.addFormDataPart("imgurl",file.getName(), RequestBody.create(MediaType.parse("image/jpeg"),byteArrayOutputStream.toByteArray()));
Log.i("TAG_----->path2",file.getName());
MultipartBody build = builder.build();
okhttp3.Request bi = new okhttp3.Request.Builder()
.url(ActivityUrl.SHOWYUYUE)//URL
.post(build)
.build();
client.newCall(bi).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("TAG", "onFailure: 失败");
}
@Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
String result=response.body().string();
//okhttp中不能解析JSON,要利用handler
Message message = handler.obtainMessage();
message.obj = result;
handler.sendMessage(message);
}
});
}
public void ClickOK(View view)
{
postImage();
}