Android 使用HttpClient和第三方MiME文件上传类库,实现文件上传
openkk
12年前
MainActivity中定义的方法
private void httpUpload() { //定义HttpClient对象 HttpClient client = new DefaultHttpClient(); //获得HttpPost对象 HttpPost post = new HttpPost("http://192.168.1.106:8001/2012/upload.php"); post.addHeader("charset", HTTP.UTF_8); //实例化 MultipartEntity me = new MultipartEntity(); try { me.addPart("content",new StringBody("12cccafasdfasdf")); me.addPart("title",new StringBody("csdnliwei")); me.addPart("local",new StringBody("beijing")); //设置流文件 me.addPart("file", new InputStreamBody(new FileInputStream("/mnt/sdcard/test.jpg"), "image/pjpeg", "fengjie.jpg")); post.setEntity(me); //获得响应消息 HttpResponse resp = client.execute(post); if(resp.getStatusLine().getStatusCode()==200){ Toast.makeText(this, "文件上传文成!", 1).show(); } } catch (Exception e) { e.printStackTrace(); } }
服务器端PHP程序:
<?php header("Content-type:text/html;charset=utf-8"); print_r($_FILES['file']); $filename = $_FILES['file']['name']; if(!$_FILES['file']['error']){ if(move_uploaded_file($_FILES['file']['tmp_name'],"./upload/".$filename)){ echo "文件上传成功"; }else{ echo "文件上传失败le"; } }else{ echo "文件上传错误"; } ?>
就这样就ok,实现文件上传
转自:http://blog.csdn.net/liwei3gjob/article/details/7870360