当前位置: 移动技术网 > 移动技术>移动开发>Android > Android拍照上传功能示例代码

Android拍照上传功能示例代码

2019年07月24日  | 移动技术网移动技术  | 我要评论

本文实例讲述了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, object>();
    map.put("itemimage", 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,0, 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,0, r.string.take_photo);
  menu.add(0, upload_photo_id,0, r.string.upload_photo);
  menu.add(0, back_id,0, 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, 0, buffersize);
      while (bytesread > 0) {
        dos.write(buffer, 0, buffersize);
        bytesavailable = fileinputstream.available();
        buffersize = math.min(bytesavailable, maxbuffersize);
        bytesread = fileinputstream.read(buffer, 0, 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, funcselector.class);
  i.putextra(key_login_name, 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 , httpservletresponse response) throws ioexception, 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, 0, 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程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网