Android拍照上传功能示例代码

本文实例讲述了Android实现拍照上传功能的方法。分享给大家供大家参考,具体如下:

1、LoginWindow.java --登录窗口

package com.hemi.rhet;
import com.hemi.rhet.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
public class LoginWindow extends Activity {
 @Override
 public void onCreate(Bundle savedInstanceState) {
  System.out.println("enter LoginWindow.onCreate()!");
  super.onCreate(savedInstanceState);
  setContentView(R.layout.login_window);
  mUserName = (EditText)findViewById(R.id.username);
  mUserPasswd = (EditText)findViewById(R.id.userpasswd);
  cbx_cmwap = (CheckBox) findViewById(R.id.cbx_cmwap);
  loginButton = (Button) findViewById(R.id.login_button);
  exitButton = (Button) findViewById(R.id.exit_button);
  loginBtnListener = new View.OnClickListener() {
   public void onClick(View view) {
    LoginWindow.isCmwap = cbx_cmwap.isChecked();
    if (view == loginButton) {
      launchFetion();
    } else if(view == exitButton) {
     finish();
    }
   }
  };
  loginButton.setOnClickListener(loginBtnListener);
  exitButton.setOnClickListener(loginBtnListener);
 }
 private void launchFetion() {
  Intent i = new Intent(this,FuncSelector.class);
  i.putExtra(KEY_LOGIN_NAME,mUserName.getText().toString());
  i.putExtra(KEY_LOGIN_PASSWD,mUserPasswd.getText().toString());
  i.putExtra(KEY_LOGIN_TYPE,cbx_cmwap.isChecked());
  startActivity(i);
 }
 @Override
 public boolean onKeyDown(int keyCode,KeyEvent msg) {
//  System.out.println("enter onKeyDown() in LoginWindow!");
//
//  if (null != loginBtnListener) {
//   View aview = getCurrentFocus();
//   loginBtnListener.onClick(aview);
//  }
  return false;
 }
 private Button loginButton,exitButton;
 private EditText mUserName;
 private EditText mUserPasswd;
 private CheckBox cbx_cmwap;
 private OnClickListener loginBtnListener;
 public static final String KEY_LOGIN_NAME = "login_name";
 public static final String KEY_LOGIN_PASSWD = "login_passwd";
 public static final String KEY_LOGIN_TYPE = "login_type";
 public static boolean isCmwap = false;
}

2. FuncSelector.java -- 功能模块选择窗口

package com.hemi.rhet;
import java.util.ArrayList;
import java.util.HashMap;
import com.hemi.rhet.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;
public class FuncSelector extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    Log.i("info","enter LoginWindow.onCreate()!");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.func_selector);
    initFuncGrids();
  }
  private void initFuncGrids() {
    GridView funcSeleView = (GridView) findViewById(R.id.func_selector);
    // 生成动态数组,并且转入数据
    ArrayList<HashMap<String,Object>> lstImageItem = new ArrayList<HashMap<String,Object>>();
    HashMap<String,Object> map = new HashMap<String,Object>();
    map.put("ItemImage",R.drawable.photo_upload);      // 添加图像资源的ID
    map.put("ItemText",getString(R.string.photo_upload));  // 按序号做ItemText
    lstImageItem.add(map);
    map = new HashMap<String,R.drawable.icon);
    map.put("ItemText",getString(R.string.sys_config));
    lstImageItem.add(map);
    for (int i = 1; i <= 10; i++) {
      map = new HashMap<String,Object>();
      map.put("ItemImage",R.drawable.icon);      // 添加图像资源的ID
      map.put("ItemText","NO." + String.valueOf(i));  // 按序号做ItemText
      lstImageItem.add(map);
    }
    // 生成适配器的ImageItem <====> 动态数组的元素,两者一一对应
    SimpleAdapter saImageItems = new SimpleAdapter(this,// 没什么解释
        lstImageItem,// 数据来源
        R.layout.night_item,// night_item的XML实现
        // 动态数组与ImageItem对应的子项
        new String[] { "ItemImage","ItemText" },// ImageItem的XML文件里面的一个ImageView,两个TextView ID
        new int[] {R.id.ItemImage,R.id.ItemText});
        //null);
    // 添加并且显示
    funcSeleView.setAdapter(saImageItems);
    //saImageItems.notifyDataSetChanged();
    // 添加消息处理
    funcSeleView.setOnItemClickListener(new ItemClickListener());
  }
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
  menu.add(0,EXIT_ID,R.string.back_button);
  return true;
  }
  //@Override
 public boolean onMenuItemSelected(int featureId,MenuItem item) {
   boolean result = true;
  switch(item.getItemId()) {
  case EXIT_ID:
    this.finish();
    break;
    default:
      result = super.onMenuItemSelected(featureId,item);
      break;
    }
  return result;
 }
  // 当AdapterView被单击(触摸屏或者键盘),则返回的Item单击事件
  class ItemClickListener implements OnItemClickListener {
    public void onItemClick(AdapterView<?> arg0,// The AdapterView where the
        // click happened
        View arg1,// The view within the AdapterView that was clicked
        int arg2,// The position of the view in the adapter
        long arg3// The row id of the item that was clicked
    ) {
      // 在本例中arg2=arg3
      HashMap<String,Object> item = (HashMap<String,Object>) arg0
          .getItemAtPosition(arg2);
      String tmpStr = (String) item.get("ItemText");
      //item.put("ItemText",tmpStr + tmpStr.substring(tmpStr.length() - 1));
      // 显示所选Item的ItemText
      // setTitle((String)item.get("ItemText"));
      Log.i("info",(String) item.get("ItemText"));
      ((SimpleAdapter) arg0.getAdapter()).notifyDataSetChanged();
      Intent i;
      switch (arg2) {
      case 0:
        i = new Intent();
        i.setClass(FuncSelector.this,PhotoUpload.class);
        startActivity(i);
        break;
      case 1:
        i = new Intent();
        i.setClass(FuncSelector.this,ConfigWindow.class);
        startActivity(i);
        break;
      default:
        break;
      }
    }
  }
  private static final int TAKE_PHOTO_ID = Menu.FIRST;
 private static final int UPLOAD_PHOTO_ID = Menu.FIRST + 1;
 private static final int EXIT_ID = Menu.FIRST + 3;
}//FuncSelector

3. PhotoUpload.java -- 照片上传模块

package com.hemi.rhet;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import com.hemi.rhet.R;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class PhotoUpload extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    Log.i("info","enter LoginWindow.onCreate()!");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.func_selector);
  }
  @Override
  protected void onActivityResult(int requestCode,int resultCode,Intent data) {
    super.onActivityResult(requestCode,resultCode,data);
    if (TAKE_PHOTO_ID == requestCode) {
      if (resultCode != RESULT_OK) return;
      Bundle extras = data.getExtras();
      try {
        Bitmap photoCaptured = (Bitmap) extras.get("data");
        ImageView img = new ImageView(this);
        img.setImageBitmap(photoCaptured);
        setContentView(img);
        //store to sd card
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        photoCaptured.compress(Bitmap.CompressFormat.JPEG,100,baos);
        byte[] photoBytes = baos.toByteArray();
        File aFile = new File(getDatedFName(SD_CARD_TEMP_DIR));
        photoPath = aFile.getAbsolutePath();
        boolean b;
        if (aFile.exists()) b = aFile.delete();
        //f.mkdirs();
        aFile.createNewFile(); //need add permission to manifest
        FileOutputStream fos = new FileOutputStream(aFile);
        fos.write(photoBytes);
        fos.close();
        Log.d("info","onPictureTaken - wrote bytes: "
            + photoBytes.length);
        Uri capturedImage = Uri
            .parse(android.provider.MediaStore.Images.Media
                .insertImage(getContentResolver(),aFile
                    .getAbsolutePath(),null,null));
        Log.i("camera","Selected image: " + capturedImage.toString());
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else if (UPLOAD_PHOTO_ID == requestCode) {
    }
  }
 public boolean onCreateOptionsMenu(Menu menu) {
  super.onCreateOptionsMenu(menu);
  menu.add(0,TAKE_PHOTO_ID,R.string.take_photo);
  menu.add(0,UPLOAD_PHOTO_ID,R.string.upload_photo);
  menu.add(0,BACK_ID,R.string.back_button);
  return true;
 }
 //@Override
 public boolean onMenuItemSelected(int featureId,MenuItem item) {
   boolean result = true;
  switch(item.getItemId()) {
  case TAKE_PHOTO_ID:
      Log.i("info","ready to take photos!");
      Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
      startActivityForResult(i,TAKE_PHOTO_ID);
      result = true;
      break;
  case UPLOAD_PHOTO_ID:
    uploadFile2Svr();
    break;
  case BACK_ID:
    this.finish();
    break;
    default:
      result = super.onMenuItemSelected(featureId,item);
      break;
    }
  return result;
 }
 public void uploadFile2Svr() {
   HttpClient httpclient = new DefaultHttpClient();
   String urlStr = new StringBuffer().append(HTTP_PROTOCOL)
     .append(/*SERVER_IP*/ConfigWindow.getServerIp())
     .append(':')
     .append(/*SERVER_PORT*/ConfigWindow.getServerPort())
     .append(FILE_UPLOADER_URL)
     .toString();
    HttpPost httppost = new HttpPost(urlStr);
    String uploadMsg = "上传 照片失败!";
   try {
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     // Your DATA
     nameValuePairs.add(new BasicNameValuePair("filename",("IMAGE.jpg")) );
//    nameValuePairs.add(new BasicNameValuePair("orderno","1"));
//    nameValuePairs.add(new BasicNameValuePair("userid","123"));
//    nameValuePairs.add(new BasicNameValuePair("attach_type","1"));
//   httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
     File aFile = new File(photoPath);
     Log.i("info -- photoPath: ",photoPath);
     FileEntity fileEty = new FileEntity(aFile,"binary/octet-stream");
     httppost.setEntity(fileEty);
     httppost.addHeader("filename",/*("IMAGE.jpg")*/aFile.getName());
      HttpResponse response;
      response = httpclient.execute(httppost);
      //Log.i("info -- response: ",response.getStatusLine().getReasonPhrase());
      Header[] headers = response.getAllHeaders();
      headers = response.getHeaders("resultcode");
      if (headers[0].getValue().equals("0")) {
        uploadMsg = "上传照片成功!";
      }
    } catch (UnsupportedEncodingException e) {
      //e.printStackTrace();
      uploadMsg += e.toString();
      Log.e("exception",e.toString());
    } catch (ClientProtocolException e) {
      //e.printStackTrace();
      uploadMsg += e.toString();
      Log.e("exception",e.toString());
    } catch (IOException e) {
      //e.printStackTrace();
      uploadMsg += e.toString();
      Log.e("exception",e.toString());
    } finally {
      Toast.makeText(PhotoUpload.this,uploadMsg,Toast.LENGTH_LONG).show();
      httpclient.getConnectionManager().shutdown();
    }
 }
 public void uploadFile2Svr2() {
   BufferedReader in = null;
   HttpClient httpclient = new DefaultHttpClient();
   String urlStr = new StringBuffer().append(HTTP_PROTOCOL)
    .append(ConfigWindow.getServerIp())
    .append(ConfigWindow.getServerPort())
     .append(FILE_UPLOADER_URL)
     .toString();
   URL url = null;
    try {
      url = new URL(urlStr);
    } catch (MalformedURLException e1) {
      e1.printStackTrace();
    }
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "/r/n";
    String twoHyphens = "--";
    String boundary = "*****";
    int maxBufferSize = 16 * 1024;
    try {
//      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//      // Your DATA
//      nameValuePairs.add(new BasicNameValuePair("filename",getDatedFName("IMAGE.jpg")) );
//      nameValuePairs.add(new BasicNameValuePair("orderno","1"));
//      nameValuePairs.add(new BasicNameValuePair("userid","123"));
//      nameValuePairs.add(new BasicNameValuePair("attach_type","1"));
      //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      // Open a HTTP connection to the URL
      conn = (HttpURLConnection) url.openConnection();
      conn.setConnectTimeout(120000);
      // Allow Inputs
      conn.setDoInput(true);
      // Allow Outputs
      conn.setDoOutput(true);
      // Don't use a cached copy.
      conn.setUseCaches(false);
      // Use a post method.
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Connection","Keep-Alive");
      conn.setRequestProperty("Content-Type",//"multipart/form-data;boundary=" + boundary);
        "application/x-www-form-urlencoded");
       conn.setRequestProperty("user-agent","Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6 GTB6");
       //conn.setRequestProperty("accept-language","zh-cn,zh;q=0.5");
       //conn.setRequestProperty("Content-Type","multipart/form-data;boundary="+ boundary);
       conn.connect();
       //OutputStream connOs = conn.getOutputStream();
       dos = new DataOutputStream(conn.getOutputStream());
      dos.writeBytes(twoHyphens + boundary + lineEnd);
      dos.writeBytes("Content-Disposition: form-data; name=/"uploadedfile/";filename=/""
              + "exsistingFileName" + "/"" + lineEnd);
      //dos.writeBytes(lineEnd);
      Log.i("info","Headers are written");
      // upload file to webserver via http
      FileInputStream fileInputStream = new FileInputStream(photoPath);
      // create a buffer of maximum size
      int bytesAvailable = fileInputStream.available();
      int bufferSize = Math.min(bytesAvailable,maxBufferSize);
      byte[] buffer = new byte[bufferSize];
      // read file and write it into form...
      int bytesRead = fileInputStream.read(buffer,bufferSize);
      while (bytesRead > 0) {
        dos.write(buffer,bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable,maxBufferSize);
        bytesRead = fileInputStream.read(buffer,bufferSize);
      }
      // send multipart form data necesssary after file data...
      dos.writeBytes(lineEnd);
      dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
      // close streams
      Log.e("info","File is written");
      fileInputStream.close();
      dos.flush();
      dos.close();
      dos = null;
      // response
      // HttpResponse response;
      // response = httpclient.execute(httppost);
      // response = httpclient.execute(conn.get);
      in = new BufferedReader(
          new InputStreamReader(conn.getInputStream()));
      StringBuffer sb = new StringBuffer("");
      String line = "";
      String NL = System.getProperty("line.separator");
      while ((line = in.readLine()) != null) {
        sb.append(line + NL);
      }
      in.close();
      String result = sb.toString();
      Log.i("info",result);
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally{
   if(in != null){
    try{
     in.close();
    }catch(IOException ioe){
     Log.e("error",ioe.toString());
    }
   }
    }
 }
 public static String getDatedFName(String fname) {
    StringBuffer result = new StringBuffer();
    SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");
    String dateSfx = "_" + df.format(new Date());
    int idx = fname.lastIndexOf('.');
    if (idx != -1) {
      result.append(fname.substring(0,idx));
      result.append(dateSfx);
      result.append(fname.substring(idx));
    } else {
      result.append(fname);
      result.append(dateSfx);
    }
    return result.toString();
  }
  //=============================================
 //private Bitmap photoCaptured;
 private String photoPath = "/sdcard/IMAGE_100225083437.jpg"; //"/sdcard/1.txt";
   private static final int TAKE_PHOTO_ID = Menu.FIRST;
 private static final int UPLOAD_PHOTO_ID = Menu.FIRST + 1;
 private static final int BACK_ID = Menu.FIRST + 3;
 private static final String HTTP_PROTOCOL = "http://";
 private static final String FILE_UPLOADER_URL = "/fileuploader/system/fileUpload";
 private String SD_CARD_TEMP_DIR = Environment.getExternalStorageDirectory() + File.separator + "IMG.jpg";
}

4. ConfigWindow.java--系统配置窗口

package com.hemi.rhet;
import com.hemi.rhet.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
public class ConfigWindow extends Activity {
 @Override
 public void onCreate(Bundle savedInstanceState) {
  System.out.println("enter ConfigWindow.onCreate()!");
  super.onCreate(savedInstanceState);
  setContentView(R.layout.config_window);
  mServerIP = (EditText)findViewById(R.id.serverip);
  mServerPort = (EditText)findViewById(R.id.serverport);
  //hemerr
  mServerIP.setText(serverIp);
  mServerPort.setText(serverPort);
  okButton = (Button) findViewById(R.id.ok_button);
  backButton = (Button) findViewById(R.id.back_button);
  loginBtnListener = new View.OnClickListener() {
   public void onClick(View view) {
    if (view == okButton) {
      serverIp = mServerIP.getText().toString();
      serverPort = mServerPort.getText().toString();
      Log.i("info","IP is: "+serverIp+"/tPort is: "+serverPort);
      finish();
    } else if(view == backButton) {
      finish();
    }
   }
  };
  okButton.setOnClickListener(loginBtnListener);
  backButton.setOnClickListener(loginBtnListener);
 }
 private void launchFetion() {
  Intent i = new Intent(this,mServerIP.getText().toString());
  i.putExtra(KEY_LOGIN_PASSWD,mServerPort.getText().toString());
  startActivity(i);
 }
 @Override
 public boolean onKeyDown(int keyCode,KeyEvent msg) {
//  System.out.println("enter onKeyDown() in LoginWindow!");
//
//  if (null != loginBtnListener) {
//   View aview = getCurrentFocus();
//   loginBtnListener.onClick(aview);
//  }
  return false;
 }
 public static String getServerIp() {
    return serverIp;
  }
  public static String getServerPort() {
    return serverPort;
  }
 private Button okButton,backButton;
 private EditText mServerIP;
 private EditText mServerPort;
 private OnClickListener loginBtnListener;
 public static final String KEY_LOGIN_NAME = "login_name";
 public static final String KEY_LOGIN_PASSWD = "login_passwd";
 public static final String KEY_LOGIN_TYPE = "login_type";
 public static String serverIp = "192.168.0.98"; //;
 public static String serverPort = "8081";
}

还需要增加bg_logo.jpg、icon.png、photo_upload.png等几个图片。

Android拍照上传程序的xml配置文件

1. login_window.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical" android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:background="@drawable/bg_logo"
  >
  <TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="20dip"
  android:layout_marginRight="20dip"
    android:text="@string/user_name"
    />
  <EditText
    android:id="@+id/username"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_marginLeft="20dip"
  android:layout_marginRight="20dip"
  android:scrollHorizontally="true"
  android:autoText="false"
  android:text="user"
  android:capitalize="none"
  android:gravity="fill_horizontal"
  android:textAppearance="?android:attr/textAppearanceMedium"
  />
  <TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="20dip"
  android:layout_marginRight="20dip"
    android:text="@string/user_passwd" />
  <EditText android:id="@+id/userpasswd"
  android:layout_width="fill_parent"
     android:layout_height="wrap_content"
  android:layout_marginLeft="20dip"
  android:layout_marginRight="20dip"
  android:scrollHorizontally="true"
  android:autoText="false"
  android:text="user"
  android:capitalize="none"
  android:gravity="fill_horizontal"
  android:password="true"
  android:textAppearance="?android:attr/textAppearanceMedium" />
  <CheckBox android:id="@+id/cbx_cmwap"
     android:text="CMWAP"
     android:checked="false"
     android:layout_marginLeft="20dip"
  android:layout_marginRight="20dip"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
  <RelativeLayout android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
  <Button android:id="@+id/login_button"
     android:text="LOGIN"
     android:layout_marginLeft="20dip"
  android:layout_marginRight="20dip"
  android:layout_alignParentRight="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
  <Button android:id="@+id/exit_button"
     android:text="EXIT"
     android:layout_marginLeft="20dip"
  android:layout_marginRight="20dip"
  android:layout_toLeftOf="@id/login_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
  </RelativeLayout>
</LinearLayout>

2. func_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/func_selector"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:numColumns="auto_fit"
 android:verticalSpacing="10dp"
 android:horizontalSpacing="10dp"
 android:columnWidth="90dp"
 android:stretchMode="columnWidth"
 android:gravity="center"
 android:background="@drawable/bg_logo"
/>

3. night_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_height="wrap_content"
   android:paddingBottom="4dip" android:layout_width="fill_parent">
   <ImageView
    android:layout_height="wrap_content"
    android:id="@+id/ItemImage"
    android:layout_width="wrap_content"
    android:layout_centerHorizontal="true">
   </ImageView>
   <TextView
    android:layout_width="wrap_content"
    android:layout_below="@+id/ItemImage"
    android:layout_height="wrap_content"
    android:text="TextView01"
    android:layout_centerHorizontal="true"
    android:id="@+id/ItemText">
   </TextView>
</RelativeLayout>

4. config_window.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical" android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="20dip"
  android:layout_marginRight="20dip"
    android:text="@string/server_ip"
    />
  <EditText
    android:id="@+id/serverip"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_marginLeft="20dip"
  android:layout_marginRight="20dip"
  android:scrollHorizontally="true"
  android:autoText="false"
  android:capitalize="none"
  android:gravity="fill_horizontal"
  android:textAppearance="?android:attr/textAppearanceMedium"
  />
  <TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="20dip"
  android:layout_marginRight="20dip"
    android:text="@string/server_port" />
  <EditText android:id="@+id/serverport"
  android:layout_width="fill_parent"
     android:layout_height="wrap_content"
  android:layout_marginLeft="20dip"
  android:layout_marginRight="20dip"
  android:scrollHorizontally="true"
  android:autoText="false"
  android:capitalize="none"
  android:gravity="fill_horizontal"
  android:textAppearance="?android:attr/textAppearanceMedium" />
  <RelativeLayout android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
  <Button android:id="@+id/ok_button"
     android:text="@string/ok_button"
     android:layout_marginLeft="20dip"
  android:layout_marginRight="20dip"
  android:layout_alignParentRight="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
  <Button android:id="@+id/back_button"
     android:text="@string/back_button"
     android:layout_marginLeft="20dip"
  android:layout_marginRight="20dip"
  android:layout_toLeftOf="@id/ok_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
  </RelativeLayout>
</LinearLayout>

5. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.hemi.rhet" android:versionCode="1" android:versionName="1.0">
  <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:label="@string/app_name" android:name="LoginWindow">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
    <activity android:name="FuncSelector"></activity>
    <activity android:name="PhotoUpload"></activity>
    <activity android:name="ConfigWindow"></activity>
  </application>
  <uses-sdk android:minSdkVersion="5"/>
  <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
</manifest>

Android拍照上传程序的Servlet程序样例

UploadFileServlet.java:

package com.hemi.rhet.servlet;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
//import org.apache.commons.fileupload.*;
//import org.apache.commons.fileupload.disk.DiskFileItemFactory;
//import org.apache.commons.fileupload.servlet.ServletFileUpload;
//import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
//import org.apache.struts2.ServletActionContext;
public class UploadFileServlet extends HttpServlet
{
 private static Logger log = Logger.getLogger(UploadFileServlet.class);
 private static final String OBLIQUE_LINE = "/";
 private static final String OPPOSITE_OBLIQUE_LINE = "////";
 private static final String WEBPOSITION = "webapps";
 private static final String SBPATH = "UploadedFiles/";
 File outdir = null;
 File outfile = null;
 FileOutputStream fos = null;
 BufferedInputStream bis = null;
 byte[] bs = new byte[1024];
 String uploadFName = null;
 String orderNo = null;
 String userId = null;
 String attachType = "2";
 public void init() throws ServletException
 {
//  if (log.isDebugEnabled())
//  {
//   log.debug("进入init()方法!!");
//  }
 }
 public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
 {
  doPost(request,response);
 }
 public void doPost(HttpServletRequest request,ServletException
 {
  String root = this.getServletContext().getRealPath("/");
  root = root.replaceAll("////","/");
  try
  {
   StringBuffer destFName = new StringBuffer();
   destFName.append(getRealDir(root)).append(SBPATH);
   outdir = new File(destFName.toString());
   request.setCharacterEncoding("UTF-8");
   uploadFName = request.getParameter("filename"); //name of uploaded file
   uploadFName = request.getHeader("filename");
   if (isEmpty(uploadFName)) uploadFName = "filename.jpg";
   //orderNo = request.getParameter("orderno");  //id of the order or work sheet
   //userId = request.getParameter("userid");  //id of the user who upload the file
   //attachType = request.getParameter("attach_type"); //type of attachment,refer to file.FileBean's definition
   String desc = request.getParameter("desc");  //description of uploaded file
   if (desc==null) desc = "";
   if (true)
   {
     destFName.append(getDatedFName(uploadFName));
    outfile = new File(destFName.toString());
    bis = new BufferedInputStream(request.getInputStream());
    uploadFile();
    //response.getWriter().write("0"); //success
    response.setHeader("resultcode","0");
   }
   else if (desc.length() > 400/2) {
     //response.getWriter().write("3"); //illegal description
     response.setHeader("resultcode","3");
   }
   else
   {
    if (log.isDebugEnabled())
    {
     log.debug("调用格式错误!");
    }
    response.sendError(100,"参数错误!");
    //response.getWriter().write("1");
    response.setHeader("resultcode","1"); //parameter error
    //return;
   }
  } catch (SQLException e) {
    if (log.isDebugEnabled()) {
    log.debug(e);
   }
    //response.getWriter().write("6"); //failure of insert to database
    response.setHeader("resultcode","6");
  } catch (Exception e) {
   if (log.isDebugEnabled()) {
    log.debug(e);
   }
   //response.getWriter().write("7"); //failure
   response.setHeader("resultcode","7");
  } finally {
   if (null != bis)
    bis.close();
   if (null != fos)
    fos.close();
  }
 }
 private void uploadFile() throws IOException
 {
  if (log.isDebugEnabled())
  {
   log.debug("outdir:" + outdir.getPath());
   log.debug("outfile:" + outfile.getPath());
  }
  if (!outdir.exists())
   outdir.mkdir();
  if (!outfile.exists())
   outfile.createNewFile();
  fos = new FileOutputStream(outfile);
  int i;
  while ((i = bis.read(bs)) != -1)
  {
   fos.write(bs,i);
  }
 }
 public static String getDatedFName(String fname) {
    StringBuffer result = new StringBuffer();
    SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");
    String dateSfx = "_" + df.format(new Date());
    int idx = fname.lastIndexOf('.');
    if (idx != -1) {
      result.append(fname.substring(0,idx));
      result.append(dateSfx);
      result.append(fname.substring(idx));
    } else {
      result.append(fname);
      result.append(dateSfx);
    }
    return result.toString();
  }
  public static String getUrlFName(String fname,HttpServletRequest request) {
    String result = "";
    if (isEmpty(fname)) return result;
    try {
      if (fname.startsWith("http://")) {
        result = fname;
      } else {
        //HttpServletRequest request = ServletActionContext.getServletContext().getRgetRequest();
        //UserAndOrganAndRole user = (UserAndOrganAndRole)request.getSession().getAttribute("user");
        String ip = request.getServerName();
        int port = request.getServerPort();
        result = fname.substring(fname.indexOf(UploadFileServlet.SBPATH));
        StringBuffer tmpBuff = new StringBuffer();
        tmpBuff.append("http://").append(ip).append(":").append(port).append(OBLIQUE_LINE).append(result);
        //Sample: http://localhost:8083/UploadedFiles/IMAGE_067_100222102521.jpg
        result = tmpBuff.toString();
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    System.out.println("result is: "+result);
    return result;
  }
  public static boolean isEmpty(String str) {
    return ((str == null) || (str.length() == 0));
  }
 /**
  * Method getRealDir search webapps position
  *
  * @param despath
  *
  * @return
  *
  */
 private String getRealDir(String newFileNameRoot) throws Exception {
  if (newFileNameRoot == null)
   throw new Exception("get real dir failed !");
  int dp = newFileNameRoot
    .lastIndexOf(OBLIQUE_LINE);
  if (dp == -1)
   throw new Exception("invalid path !");
  int dpbefore = newFileNameRoot.lastIndexOf(
    OBLIQUE_LINE,dp - 1);
  if (dpbefore == -1)
   throw new Exception("invalid path !");
  String needSubStr = newFileNameRoot.substring(dpbefore + 1,dp);
  String nextStr = newFileNameRoot.substring(0,dpbefore + 1);
  if (!needSubStr.trim().equals(WEBPOSITION)) {
   return getRealDir(nextStr);
  } else
   return newFileNameRoot;
 }
 public static void main(String[] args)
 {
 }
}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
  xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
  http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 <servlet>
  <servlet-name>Upload</servlet-name>
  <servlet-class>com.hemi.rhet.servlet.UploadFileServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>Upload</servlet-name>
  <url-pattern>/system/fileUpload</url-pattern>
 </servlet-mapping>
</web-app>

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android拍照与图片处理技巧总结》、《Android开发入门与进阶教程》、《Android多媒体操作技巧汇总(音频,视频,录音等)》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结

希望本文所述对大家Android程序设计有所帮助。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


AdvserView.java package com.earen.viewflipper; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory;
ImageView的scaleType的属性有好几种,分别是matrix(默认)、center、centerCrop、centerInside、fitCenter、fitEnd、fitStart、fitXY。 |值|说明| |:--:|:--| |center|保持原图的大小,显示在ImageVie
文章浏览阅读8.8k次,点赞9次,收藏20次。本文操作环境:win10/Android studio 3.21.环境配置 在SDK Tools里选择 CMAKE/LLDB/NDK点击OK 安装这些插件. 2.创建CMakeLists.txt文件 在Project 目录下,右键app,点击新建File文件,命名为CMakeLists.txt点击OK,创建完毕! 3.配置文件 在CMa..._link c++ project with gradle
文章浏览阅读1.2w次,点赞15次,收藏69次。实现目的:由mainActivity界面跳转到otherActivity界面1.写好两个layout文件,activity_main.xml和otherxml.xmlactivity_main.xml&lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;RelativeLayout ="http://schemas..._android studio 界面跳转
文章浏览阅读3.8w次。前言:最近在找Android上的全局代理软件来用,然后发现了这两款神作,都是外国的软件,而且都是开源的软件,因此把源码下载了下来,给有需要研究代理这方面的童鞋看看。不得不说,国外的开源精神十分浓,大家相互使用当前基础的开源软件,然后组合成一个更大更强的大开源软件。好吧,废话不多说,下面简单介绍一下这两款开源项目。一、ProxyDroid:ProxyDroid功能比较强大,用到的技术也比较多,源码也_proxydroid
文章浏览阅读2.5w次,点赞17次,收藏6次。创建项目后,运行项目时Gradle Build 窗口却显示错误:程序包R不存在通常情况下是不会出现这个错误的。我是怎么遇到这个错误的呢?第一次创建项目,company Domain我使用的是:aven.com,但是创建过程在卡在了Building 'Calculator' Gradle Project info这个过程中,于是我选择了“Cancel”第二次创建项目,我还是使用相同的项目名称和项目路_r不存在
文章浏览阅读8.9w次,点赞4次,收藏43次。前言:在Android上使用系统自带的代理,限制灰常大,仅支持系统自带的浏览器。这样像QQ、飞信、微博等这些单独的App都不能使用系统的代理。如何让所有软件都能正常代理呢?ProxyDroid这个软件能帮你解决!使用方法及步骤如下:一、推荐从Google Play下载ProxyDroid,目前最新版本是v2.6.6。二、对ProxyDroid进行配置(基本配置:) (1) Auto S_proxydroid使用教程
文章浏览阅读1.1w次,点赞4次,收藏17次。Android Studio提供了一个很实用的工具Android设备监视器(Android device monitor),该监视器中最常用的一个工具就是DDMS(Dalvik Debug Monitor Service),是 Android 开发环境中的Dalvik虚拟机调试监控服务。可以进行的操作有:为测试设备截屏,查看特定进程中正在运行的线程以及堆栈信息、Logcat、广播状态信息、模拟电话_安卓摄像头调试工具
文章浏览阅读2.1k次。初学Android游戏开发的朋友,往往会显得有些无所适从,他们常常不知道该从何处入手,每当遇到自己无法解决的难题时,又往往会一边羡慕于 iPhone下有诸如Cocos2d-iphone之类的免费游戏引擎可供使用,一边自暴自弃的抱怨Android平台游戏开发难度太高,又连个像样的游 戏引擎也没有,甚至误以为使用Java语言开发游戏是一件费力不讨好且没有出路的事情。事实上,这种想法完全是没有必_有素材的游戏引擎
文章浏览阅读3.2k次,点赞2次,收藏2次。2014年12月从csdn专家福利获得的一本书《Android游戏开发技术实战详解》,尘封了一年多的时间,今天才翻开来看。我认识中的Android,提到Android最先浮现在我脑海中的是那可爱的机器人图标:这个Logo是由Ascender公司设计的,诞生于2010年,其设计灵感源于男女厕所门上的图形符号(真的是灵感无处不在),于是布洛克绘制了一个简单的机器人,它的躯干就像锡罐的形状,头上还有两根_智能手机的特点有哪些?
文章浏览阅读8.1k次,点赞9次,收藏11次。首先,Android是不是真的找工作越来越难呢?这个可能是大家最关心的。这个受大的经济环境以及行业发展前景的影响,同时也和个人因素有关。2016-08-26近期一方面是所在的公司招聘Java开发人员很难招到合适的,投简历的人很少;而另一方面,经常听身边的人说Android、iOS方面找工作不好找,特别是没什么经验的,经验比较少的!说是不好找,但在我家所在的吉林省省会长春,会Unity3D+Maya_android 开发和asp.net哪个好 site:blog.csdn.net
文章浏览阅读6.1k次。在上篇“走进Android开发的世界,HelloWorld”,我们创建了一个Android 项目 HelloWorld,并演示了如何通过USB连接手机查看运行效果;而如果没有手机或没有对应型号的手机,又想做对应型号(屏幕尺寸、Android系统版本)的适配,应该怎么办呢?这时Android模拟器就派上用场了。Android模拟器Android SDK自带一个移动模拟器。它是一个可以运行在你电脑上的_安卓移动开发软件怎样预览
文章浏览阅读8.9k次。Google IO 2017 上宣布,将Kotlin语言作为安卓开发的官方语言。Kotlin由JetBrains公司开发,与Java 100%互通,并具备诸多Java尚不支持的新特性。谷歌称还将与JetBrains公司合作,为Kotlin设立一个非盈利基金会。Kotlin 是一个基于 JVM 的静态类型编程语言,Kotlin可以编译成Java字节码,也可以编译成JavaScript,方便在没有JV_kotlin为什么被嫌弃
文章浏览阅读9.6w次,点赞17次,收藏35次。有些情况下,不方便使用断点的方式来调试,而是希望在控制台打印输出日志,使用过Eclipse的同学都知道Java可以使用 System.out.println(""); 来在控制台打印输出日志,但是在android studio中却是不行的,还是有差别的,那应该用什么呢?android.util.Log在调试代码的时候我们需要查看调试信息,那我们就需要用Android Log类。android.ut_andirod.studio 为什么不在控制台打印输出
文章浏览阅读8.2k次,点赞2次,收藏8次。在上篇“走进Android开发的世界,HelloWorld”,我们创建了一个Android 项目 HelloWorld,并演示了如何通过USB连接手机查看运行效果;这里讲一下如何为应用添加一个按钮,并为按钮添加Click单击事件处理程序,显示/隐藏另一个按钮。添加按钮在HelloWorld项目的基础上,打开界面布局文件:activity_main.xml切换到Design(设计)模式;在组件But_activity_main.xml按钮隐藏
文章浏览阅读2.9k次,点赞3次,收藏9次。android 开发工具主流的还是Android Studio,当然也有很多人喜欢用Eclipse,也有人喜欢用IntelliJ IDEA ;还有Xamarin这种只需要编写一次代码,可以编译多种平台可运行的强大工具。但是它又真的强大吗?就我看来没有,身边很多人还是在用Android Studio、XCode开发应用,没见谁在用Xamarin之类的工具。系统要求WindowsMicrosoft®_android开发下载安装
文章浏览阅读4.2k次,点赞7次,收藏26次。你知道Hello World程序的由来吗?对于大多数编程语言的学习来说,真正入门的一课就是 Hello World!会而不难,难而不会。虽然很多人写过关于Android开发Hello World的文章,但随着时间的推移,开发工具、技术的进步,可能有些已经过时了。我就记录一下当下我所经历的第一个Android APP HelloWorld。一、准备1、开发环境参考:Android Studio 下载_android helloworld textview 句柄获取
这篇“android轻量级无侵入式管理数据库自动升级组件怎么实现”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定...
今天小编给大家分享一下Android实现自定义圆形进度条的常用方法有哪些的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文...
这篇文章主要讲解了“Android如何解决字符对齐问题”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Android...