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
- Android简单实现将手机图片上传到服务器中
- android将图片上传到php服务器
- 安卓实现拍照、在手机中选择图片通过webservice上传图片到服务器
- 安卓实现拍照、在手机中选择图片通过webservice上传图片到服务器
- android实现简单的图片上传服务器
- Android中上传图片到服务器详解
- 上传android手机图片到服务器的方法
- winform中如何将本地图片上传到服务器
- java中怎么将本地图片上传到服务器上
- android 上传图片到服务器
- Android: 上传图片到服务器
- Android上传图片到服务器
- Android 上传图片到服务器
- android上传图片到服务器
- Android上传图片到服务器
- android上传图片到服务器
- Android 上传图片到服务器
- android 上传图片到服务器
- Android简单调用相机Camera功能,实现打开照相功能
- Mybatis/Ibatis,数据库操作的返回值
- PHP 获取数组值中最大的数据
- Android简单实现Socket通信,客户端连接服务器后,服务器向客户端发送文字数据
- Android调用相机拍摄照片并显示到 ImageView控件中
- Android简单实现将手机图片上传到服务器中
- PHP修改PHP.ini上传大文件的解决办法
- Android获取当前位置的三种方式及其使用方法
- Android中获取当前位置的使用步骤
- Android获取当前位置,推荐使用百度地图SDK获取位置
- Android中几种常用的弹窗信息提示方式
- Mysql命令行修改字段类型
- Jq获取同一名称单选框(radio)被选中的值
- 关于301跳转的多种办法