Android简单实现将手机图片上传到服务器中
生活随笔
收集整理的這篇文章主要介紹了
Android简单实现将手机图片上传到服务器中
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
在本例中,將會簡單的實現(xiàn)安卓手機將圖片上傳到服務(wù)器中,本例使用到了 服務(wù)器端:PHP+APACHE 客戶端:JAVA 先簡單實現(xiàn)一下服務(wù)器端的上傳并測試上傳效果,看實例
<?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);
}
?> 在上述代碼中很容易的就已經(jīng)將圖片上傳到服務(wù)器中,同時需要注意的是,在真實的操作過程中,這段代碼是不可以直接拿來用的,需要對其進行更多的功能擴展,比如說驗證圖片是否允許上傳,驗證圖片大小等等。 接下來,再看一下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;//將要綁定到創(chuàng)建他的線程中(一般是位于主線程)
private MultipartEntity multipartEntity;
private Boolean isUpload = false;//判斷是否上傳成功
private TextView tv;
private String sImagePath;//服務(wù)器端返回路徑@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();//獲取通信狀態(tài)
if (httpStatus == HttpStatus.SC_OK) {
JSONObject jsonObject = parseJSON(content);//解析字符串為JSON對象
String status = jsonObject.getString("status");//獲取上傳狀態(tài)
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 = 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;
}} 因為是簡單實現(xiàn),也能更通俗的理解,這里并沒有對操作網(wǎng)絡(luò)以及通用函數(shù)進行封裝,所以可以直接拷貝此段代碼到自己的應(yīng)用程序中進行稍微的修改就可以直接運行,在這里定義的服務(wù)器返回路徑可以自己修改為URL路徑,這樣可以在返回的Activity中我們可以實現(xiàn)將剛才上傳成功的照片顯示在客戶端中,下面再看一下布局文件 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> 最好,就是權(quán)限問題了,因為操作了網(wǎng)絡(luò),所以不能忘記將INTERNET權(quán)限加上,看一下 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> 這樣來說,就可以使用手機將圖片上傳到服務(wù)器中了。
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎
總結(jié)
以上是生活随笔為你收集整理的Android简单实现将手机图片上传到服务器中的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android调用相机拍摄照片并显示到
- 下一篇: Android获取当前位置的三种方式及其