Android简单实现将手机图片上传到server中

犀渠玉剑良家子,白马金羁侠少年。这篇文章主要讲述Android简单实现将手机图片上传到server中相关的知识,希望能为你提供帮助。
在本例中。将会简单的实现安卓手机将图片上传到server中。本例使用到了server端:php+APACHE客户端:java先简单实现一下server端的上传并測试上传效果,看实例

< ?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="https://www.songbingjia.com/android/确定上传"> < /form> < ?
【Android简单实现将手机图片上传到server中】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); } ?>

在上述代码中非常easy的就已经将图片上传到server中,同一时候须要注意的是,在真实的操作过程中,这段代码是不能够直接拿来用的,须要对其进行很多其它的功能扩展,比方说验证图片是否同意上传,验证图片大小等等。接下来,再看一下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; //server端返回路径@Override protected 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() {@Override public void onClick(View arg0) { // TODO Auto-generated method stub new 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 block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } handler.post(new Runnable() {@Override public void run() { // TODO Auto-generated method stub if (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 = https://www.songbingjia.com/android/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 block e.printStackTrace(); } return result; }@Override public 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; }}

由于是简单实现,也能更通俗的理解,这里并没有对操作网络以及通用函数进行封装,所以能够直接拷贝此段代码到自己的应用程序中进行略微的改动就能够直接执行,在这里定义的server返回路径能够自己改动为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" > < TextView android: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" /> < Button android: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-sdk android:minSdkVersion="8" android:targetSdkVersion="16" /> < uses-permission android:name="android.permission.INTERNET" /> < application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > < activity android: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>

这样来说,就能够使用手机将图片上传到server中了。

    推荐阅读