Android简单实现将手机图片上传到服务器中

来源:互联网 发布:华为智能遥控软件 编辑:程序博客网 时间:2024/04/28 10:55
在本例中,将会简单的实现安卓手机将图片上传到服务器中,本例使用到了服务器端:PHP+APACHE客户端:JAVA先简单实现一下服务器端的上传并测试上传效果,看实例
<?php if(empty($_GET['submit'])){?><form enctype="multipart/form-data" action="<?php $_SERVER['PHP_SELF']?>?submit=1" method="post">Send this file: <input name="filename" type="file"><input type="submit" value="确定上传"></form><?php}else{$path="E:\ComsenzEXP\wwwroot\uploadfiles/";if(!file_exists($path)){mkdir("$path", 0700);}$file2 = $path.time().".jpg";$result = move_uploaded_file($_FILES["filename"]["tmp_name"],$file2);if($result){$return = array('status'=>'true','path'=>$file2);}else{$return = array('status'=>'false','path'=>$file2);}echo json_encode($return);}?>
在上述代码中很容易的就已经将图片上传到服务器中,同时需要注意的是,在真实的操作过程中,这段代码是不可以直接拿来用的,需要对其进行更多的功能扩展,比如说验证图片是否允许上传,验证图片大小等等。接下来,再看一下Android主程序MainActivity.java
package com.example.androidupload;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.IOException;import java.io.InputStream;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.mime.MultipartEntity;import org.apache.http.entity.mime.content.ContentBody;import org.apache.http.entity.mime.content.FileBody;import org.apache.http.impl.client.DefaultHttpClient;import org.json.JSONException;import org.json.JSONObject;import org.json.JSONTokener;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.app.Activity;import android.util.Log;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity {private String imagePath;//将要上传的图片路径private Handler handler;//将要绑定到创建他的线程中(一般是位于主线程)private MultipartEntity multipartEntity;private Boolean isUpload = false;//判断是否上传成功private TextView tv;private String sImagePath;//服务器端返回路径@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);imagePath = Environment.getExternalStorageDirectory() + File.separator+ "tmp.jpg";handler = new Handler();//绑定到主线程中Button btn = (Button) findViewById(R.id.button1);btn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubnew Thread() {public void run() {File file = new File(imagePath);multipartEntity = new MultipartEntity();ContentBody contentBody = new FileBody(file,"image/jpeg");multipartEntity.addPart("filename", contentBody);HttpPost httpPost = new HttpPost("http://192.168.1.100/x.php?submit=1");httpPost.setEntity(multipartEntity);HttpClient httpClient = new DefaultHttpClient();try {HttpResponse httpResponse = httpClient.execute(httpPost);InputStream in = httpResponse.getEntity().getContent();String content = readString(in);int httpStatus = httpResponse.getStatusLine().getStatusCode();//获取通信状态if (httpStatus == HttpStatus.SC_OK) {JSONObject jsonObject = parseJSON(content);//解析字符串为JSON对象String status = jsonObject.getString("status");//获取上传状态sImagePath = jsonObject.getString("path");Log.d("MSG", status);if (status.equals("true")) {isUpload = true;}}Log.d("MSG", content);Log.d("MSG", "Upload Success");} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}handler.post(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubif (isUpload) {tv = (TextView)findViewById(R.id.textView1);tv.setText(sImagePath);Toast.makeText(MainActivity.this, "上传成功",Toast.LENGTH_SHORT).show();} else {Toast.makeText(MainActivity.this, "上传失败",Toast.LENGTH_SHORT).show();}}});}}.start();}});}protected String readString(InputStream in) throws Exception {byte[] data = new byte[1024];int length = 0;ByteArrayOutputStream bout = new ByteArrayOutputStream();while ((length = in.read(data)) != -1) {bout.write(data, 0, length);}return new String(bout.toByteArray(), "GBK");}protected JSONObject parseJSON(String str) {JSONTokener jsonParser = new JSONTokener(str);JSONObject result = null;try {result = (JSONObject) jsonParser.nextValue();} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}return result;}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.activity_main, menu);return true;}}
因为是简单实现,也能更通俗的理解,这里并没有对操作网络以及通用函数进行封装,所以可以直接拷贝此段代码到自己的应用程序中进行稍微的修改就可以直接运行,在这里定义的服务器返回路径可以自己修改为URL路径,这样可以在返回的Activity中我们可以实现将刚才上传成功的照片显示在客户端中,下面再看一下布局文件activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity" ><TextViewandroid:id="@+id/textView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:layout_centerVertical="true"android:text="@string/hello_world" /><Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_alignParentTop="true"android:layout_marginRight="19dp"android:layout_marginTop="36dp"android:text="Button" /></RelativeLayout>
最好,就是权限问题了,因为操作了网络,所以不能忘记将INTERNET权限加上,看一下AndroidMainFest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.androidupload"android:versionCode="1"android:versionName="1.0" ><uses-sdkandroid:minSdkVersion="8"android:targetSdkVersion="16" /><uses-permission android:name="android.permission.INTERNET" /><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid:name="com.example.androidupload.MainActivity"android:label="@string/app_name" ><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>
这样来说,就可以使用手机将图片上传到服务器中了。
1 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 用钱宝逾期未还怎么办 支付宝被冻结怎么办啊 借钱没借条不还怎么办 借贷宝换号码了怎么办 借贷宝还不起了怎么办 花钱如流水的人怎么办 手机贷登录不上怎么办 如果被网上追逃怎么办 5s指纹排线断了怎么办 苹果6s指纹坏了怎么办 苹果的指纹坏了怎么办 苹果7指纹坏了怎么办 苹果6指纹坏了怎么办 指纹浅打不了卡怎么办 我要贷款5万怎么办 拍拍贷一千不还怎么办 牙龈肿里面有脓怎么办 爱奇艺会员账号忘了怎么办 被私立医院坑了怎么办 在医院被坑了怎么办 流产后子宫内膜薄怎么办 人流后内膜过厚怎么办 子宫内膜薄月经量少怎么办 子宫内膜很薄该怎么办 月经量少子宫内膜薄怎么办 子宫内薄没月经怎么办 感冒20多天不好怎么办 皮肤干燥又痒怎么办了 眼周皮肤很干怎么办 产后掉头发很厉害怎么办 班上学生很吵怎么办 进了网贷黑名单怎么办 预约了挂号没去怎么办 吃完米索手心痒怎么办 三岁宝宝湿疹了怎么办 割完剥皮后水肿怎么办 微医预约挂号后怎么办 人流后出现腰疼怎么办 生育服务单丢了怎么办 客厅地面砖坏了怎么办 门锁很涩不好开怎么办