说明:使用是httpclient+MultipartEntity,因此需要导入包:httpmime-4.1.1(这个包非常重要!务必导入!)
写在前面:我只是贴出核心代码,只是记录下我寻找上传功能的过程,我是一个PHPer,最近项目需要编写APP,因此就刚学习Android开发。如果你也正在学习Android可以一起交流一下~~
上代码:(安卓客户端代码)直接贴出关键部分
/*
* 图片上传
*/
private void httpUpload() {
HttpClient httpclient = new DefaultHttpClient();
// 设置通信协议版本
httpclient.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
String pathToOurFile = C.dir.images + File.separator + filename;
//要上传的图片/mnt/sdcard/images/IMG_20131026_072832.jpg
Log.w("file", pathToOurFile);
String urlServer = "http://192.168.1.180/index/upload/index.php";
HttpPost httppost = new HttpPost(urlServer);
File file = new File(pathToOurFile);
MultipartEntity mpEntity = new MultipartEntity(); // 文件传输(这个需要用到httpmime-4.1.1.jar)
ContentBody cbFile = new FileBody(file);
StringBody n = null;
try {
n = new StringBody("这里可以传递其他内容");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
mpEntity.addPart("name", n);//
mpEntity.addPart("file", cbFile); //
httppost.setEntity(mpEntity);
try {
httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
//上传成功,删除临时文件
file.delete();
Log.w("result", "上传成功!");
}
说明:我这里只是为了实现上传功能,随后需要按照服务器端的返回结果进行处理~
服务器端代码:(PHP代码)
$arrTmp = pathinfo($_FILES['file']['name']);//获取上传文件信息
$extension = strtolower($arrTmp['extension']);//获取扩展,并转成小写
$file_newname = time().".".$extension;
$result = @move_uploaded_file($_FILES['file']['tmp_name'],$file_newname);
演示过程:
保存路径
客户端
图片裁剪以及保存、
发送服务器
上传成功