放贷款需要入户拍照示例拍照

Android拍照上传功能示例代码
作者:与时俱进
字体:[ ] 类型:转载 时间:
这篇文章主要介绍了Android拍照上传功能用法,结合实例形式详细分析了Android拍照上传功能所涉及的相关知识点与功能实现技巧,需要的朋友可以参考下
本文实例讲述了Android实现拍照上传功能的方法。分享给大家供大家参考,具体如下:
1、LoginWindow.java --登录窗口
package com.hemi.
import com.hemi.rhet.R;
import android.app.A
import android.content.I
import android.os.B
import android.view.KeyE
import android.view.V
import android.view.View.OnClickL
import android.widget.B
import android.widget.CheckB
import android.widget.EditT
public class LoginWindow extends Activity {
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) {
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);
public boolean onKeyDown(int keyCode, KeyEvent msg) {
System.out.println("enter onKeyDown() in LoginWindow!");
if (null != loginBtnListener) {
View aview = getCurrentFocus();
loginBtnListener.onClick(aview);
private Button loginButton, exitB
private EditText mUserN
private EditText mUserP
private CheckBox cbx_
private OnClickListener loginBtnL
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 =
2. FuncSelector.java -- 功能模块选择窗口
package com.hemi.
import java.util.ArrayL
import java.util.HashM
import com.hemi.rhet.R;
import android.app.A
import android.content.I
import android.os.B
import android.util.L
import android.view.M
import android.view.MenuI
import android.view.V
import android.widget.AdapterV
import android.widget.GridV
import android.widget.SimpleA
import android.widget.AdapterView.OnItemClickL
public class FuncSelector extends Activity {
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});
// 添加并且显示
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);
//@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
boolean result =
switch(item.getItemId()) {
case EXIT_ID:
this.finish();
result = super.onMenuItemSelected(featureId, item);
// 当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();
switch (arg2) {
i = new Intent();
i.setClass(FuncSelector.this, PhotoUpload.class);
startActivity(i);
i = new Intent();
i.setClass(FuncSelector.this, ConfigWindow.class);
startActivity(i);
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.
import java.io.BufferedR
import java.io.ByteArrayOutputS
import java.io.DataOutputS
import java.io.F
import java.io.FileInputS
import java.io.FileNotFoundE
import java.io.FileOutputS
import java.io.IOE
import java.io.InputStreamR
import java.io.OutputS
import java.io.UnsupportedEncodingE
import java.net.HttpURLC
import java.net.MalformedURLE
import java.net.URL;
import java.text.SimpleDateF
import java.util.ArrayL
import java.util.D
import java.util.HashM
import java.util.L
import org.apache.http.H
import org.apache.http.HttpR
import org.apache.http.NameValueP
import org.apache.http.client.ClientProtocolE
import org.apache.http.client.HttpC
import org.apache.http.client.entity.UrlEncodedFormE
import org.apache.http.client.methods.HttpP
import org.apache.http.entity.FileE
import org.apache.http.impl.client.DefaultHttpC
import org.apache.http.message.BasicNameValueP
import com.hemi.rhet.R;
import android.app.A
import android.content.I
import android.graphics.B
import android.net.U
import android.os.B
import android.os.E
import android.util.L
import android.view.M
import android.view.MenuI
import android.view.V
import android.widget.AdapterV
import android.widget.GridV
import android.widget.ImageV
import android.widget.SimpleA
import android.widget.T
import android.widget.AdapterView.OnItemClickL
public class PhotoUpload extends Activity {
public void onCreate(Bundle savedInstanceState) {
Log.i("info", "enter LoginWindow.onCreate()!");
super.onCreate(savedInstanceState);
setContentView(R.layout.func_selector);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (TAKE_PHOTO_ID == requestCode) {
if (resultCode != RESULT_OK)
Bundle extras = data.getExtras();
Bitmap photoCaptured = (Bitmap) extras.get("data");
ImageView img = new ImageView(this);
img.setImageBitmap(photoCaptured);
setContentView(img);
//store to sd card
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pressFormat.JPEG, 100, baos);
byte[] photoBytes = baos.toByteArray();
File aFile = new File(getDatedFName(SD_CARD_TEMP_DIR));
photoPath = aFile.getAbsolutePath();
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);
//@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
boolean result =
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);
case UPLOAD_PHOTO_ID:
uploadFile2Svr();
case BACK_ID:
this.finish();
result = super.onMenuItemSelected(featureId, item);
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 = "上传 照片失败!";
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());
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 =
HttpClient httpclient = new DefaultHttpClient();
String urlStr = new StringBuffer().append(HTTP_PROTOCOL)
.append(ConfigWindow.getServerIp())
.append(ConfigWindow.getServerPort())
.append(FILE_UPLOADER_URL)
.toString();
url = new URL(urlStr);
} catch (MalformedURLException e1) {
e1.printStackTrace();
HttpURLConnection conn =
DataOutputStream dos =
String lineEnd = "/r/n";
String twoHyphens = "--";
String boundary = "*****";
int maxBufferSize = 16 * 1024;
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-boundary=" + boundary);
"application/x-www-form-urlencoded");
conn.setRequestProperty("user-agent",
"Mozilla/5.0 (W U; Windows NT 5.2; zh-CN; rv:1.9.1.6) Gecko/ Firefox/3.5.6 GTB6");
//conn.setRequestProperty("accept-language", "zh-cn,q=0.5");
//conn.setRequestProperty("Content-Type", "multipart/form-boundary="+ boundary);
conn.connect();
//OutputStream connOs = conn.getOutputStream();
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form- 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();
// 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){
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));
result.append(fname);
result.append(dateSfx);
return result.toString();
//=============================================
//private Bitmap photoC
private String photoPath = "/sdcard/IMAGE_.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.
import com.hemi.rhet.R;
import android.app.A
import android.content.I
import android.os.B
import android.util.L
import android.view.KeyE
import android.view.V
import android.view.View.OnClickL
import android.widget.B
import android.widget.CheckB
import android.widget.EditT
public class ConfigWindow extends Activity {
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);
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);
} else if(view == backButton) {
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);
public boolean onKeyDown(int keyCode, KeyEvent msg) {
System.out.println("enter onKeyDown() in LoginWindow!");
if (null != loginBtnListener) {
View aview = getCurrentFocus();
loginBtnListener.onClick(aview);
public static String getServerIp() {
return serverIp;
public static String getServerPort() {
return serverP
private Button okButton, backB
private EditText mServerIP;
private EditText mServerP
private OnClickListener loginBtnL
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="/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"
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="/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="/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&
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="/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"
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="/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.
import java.io.*;
import java.net.InetA
import java.net.UnknownHostE
import java.sql.SQLE
import java.text.SimpleDateF
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
//import mons.fileupload.*;
//import mons.fileupload.disk.DiskFileItemF
//import mons.fileupload.servlet.ServletFileU
//import mons.lang.time.DateU
import org.apache.log4j.L
//import org.apache.struts2.ServletActionC
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 =
File outfile =
FileOutputStream fos =
BufferedInputStream bis =
byte[] bs = new byte[1024];
String uploadFName =
String orderNo =
String userId =
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("////", "/");
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 = "";
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");
if (log.isDebugEnabled())
log.debug("调用格式错误!");
response.sendError(100, "参数错误!");
//response.getWriter().write("1");
response.setHeader("resultcode", "1"); //parameter error
} 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);
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));
result.append(fname);
result.append(dateSfx);
return result.toString();
public static String getUrlFName(String fname, HttpServletRequest request) {
String result = "";
if (isEmpty(fname))
if (fname.startsWith("http://")) {
//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_.jpg
result = tmpBuff.toString();
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("result is: "+result);
public static boolean isEmpty(String str) {
return ((str == null) || (str.length() == 0));
* Method getRealDir search webapps position
* @param despath
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);
return newFileNameR
public static void main(String[] args)
&?xml version="1.0" encoding="UTF-8"?&
&web-app version="2.4"
xmlns="/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="/xml/ns/j2ee
/xml/ns/j2ee/web-app_2_4.xsd"&
&welcome-file-list&
&welcome-file&index.jsp&/welcome-file&
&/welcome-file-list&
&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程序设计有所帮助。
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具

我要回帖

更多关于 建行装修贷款拍照要求 的文章

 

随机推荐