找传奇、传世资源到传世资源站!

Android端拍照上传至服务器(含服务器端源码)_

8.5玩家评分(1人评分)
下载后可评
介绍 评论 失效链接反馈

Android端拍照上传至服务器(含服务器端源码)_ Android平台开发-第1张

android端代码:

package com.example.take_photo_upload;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {

	private static final int PHOTO_CAPTURE = 0x11;
	private static String photoPath = "/sdcard/AnBo/";
	private static String photoName = photoPath  "laolisb.jpg";	
	Uri imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "image.jpg"));//第二个参数是临时文件,在后面将会被修改
	private Button photo, sc_photo;//拍照与下载
	private ImageView img_photo;//显示图片
	private String newName = "laoli.jpg";
	/*
	 * 这里的代码应该有问题
	 */
	private String uploadFile = "/sdcard/AnBo/laolisb.jpg";
	private String actionUrl = "http://192.168.0.104:8080/UploadPhoto1/UploadServlet";// private String actionUrl = "http://192.168.0.104:8080/File/UploadAction";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		photo = (Button) findViewById(R.id.photo);
		sc_photo = (Button) findViewById(R.id.sc_photo);
		img_photo = (ImageView) findViewById(R.id.imt_photo);
		
		/*
		 * android.os.NetworkOnMainThreadException
		 * 耗时操作,加如下代码,可在主线程中进行,但不推荐
		 */		
//		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
//		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath().build());
		sc_photo.setOnClickListener(new Sc_photo());
		photo.setOnClickListener(new Photo());
	}

	class Sc_photo implements View.OnClickListener {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			dialog();
		}

	}

	class Photo implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			
			Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
			//"/sdcard/AnBo/";
			File file = new File(photoPath);
			if (!file.exists()) { // 检查图片存放的文件夹是否存在
				file.mkdir(); // 不存在的话 创建文件夹
			}
			//photoPath  "laolisb.jpg"
			File photo = new File(photoName);
			imageUri = Uri.fromFile(photo);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); // 这样就将文件的存储方式和uri指定到了Camera应用中
			startActivityForResult(intent, PHOTO_CAPTURE);

		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		String sdStatus = Environment.getExternalStorageState();
		switch (requestCode) {
		case PHOTO_CAPTURE:
			if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
				Log.i("内存卡错误", "请检查您的内存卡");
			} else {
				BitmapFactory.Options op = new BitmapFactory.Options();
				// 设置图片的大小
				Bitmap bitMap = BitmapFactory.decodeFile(photoName);
				int width = bitMap.getWidth();
				int height = bitMap.getHeight();
				// 设置想要的大小
				int newWidth = 480;
				int newHeight = 640;
				// 计算缩放比例
				float scaleWidth = ((float) newWidth) / width;
				float scaleHeight = ((float) newHeight) / height;
				// 取得想要缩放的matrix参数
				Matrix matrix = new Matrix();
				matrix.postScale(scaleWidth, scaleHeight);
				// 得到新的图片
				bitMap = Bitmap.createBitmap(bitMap, 0, 0, width, height, matrix, true);

				// canvas.drawBitmap(bitMap, 0, 0, paint)
				// 防止内存溢出
				op.inSampleSize = 4; // 这个数字越大,图片大小越小.

				Bitmap pic = null;
				pic = BitmapFactory.decodeFile(photoName, op);
				img_photo.setImageBitmap(pic); // 这个ImageView是拍照完成后显示图片
				FileOutputStream b = null;
				;
				try {
					b = new FileOutputStream(photoName);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
				if (pic != null) {
					pic.compress(Bitmap.CompressFormat.JPEG, 50, b);
				}
			}
			break;
		default:
			return;
		}
	}

	protected void dialog() {
		
		AlertDialog.Builder builder = new Builder(MainActivity.this);
		builder.setMessage("确认上传图片吗?");

		builder.setTitle("提示");

		builder.setPositiveButton("确认", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				new Thread(new Runnable() {

					@Override
					public void run() {
						uploadPhoto();
						//uploadFile();
					}
				}).start();
			}
		});
		builder.setNegativeButton("取消", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();

			}
		});
		builder.create().show();
	}

	//第二种上传方式
	public void uploadPhoto() {
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("strParamName", "strParamValue");
		Map<String, File> files = new HashMap<String, File>();
		files.put(System.currentTimeMillis() ".jpg", new File(uploadFile));//uploadFile = "/sdcard/AnBo/laolisb.jpg";
		try {
			String str = HttpPost.post(actionUrl, params, files);
			System.out.println("str--->>>"  str);
		} catch (Exception e) {
		}
	}

	/* 上传文件至Server的方法 */
	private void uploadFile() {
		System.out.print("正在发送请求!");
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";

		Log.d("Index_Activity", "jsdj");
		try {
			URL url = new URL(actionUrl);

			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			/* 允许Input、Output,不使用Cache */
			System.out.println(con.getResponseCode()  "*********");
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);
			/* 设置传送的method=POST */
			con.setRequestMethod("POST");
			/* setRequestProperty */
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("Content-Type", "multipart/form-data;boundary="  boundary);
			/* 设置DataOutputStream */
			DataOutputStream ds = new DataOutputStream(con.getOutputStream());
			ds.writeBytes(twoHyphens  boundary  end);
			ds.writeBytes("Content-Disposition: form-data; "  "name=\"file1\";filename=\""  newName  "\""  end);
			ds.writeBytes(end);
			/* 取得文件的FileInputStream */
			FileInputStream fStream = new FileInputStream(uploadFile);
			/* 设置每次写入1024bytes */
			System.out.print("已经找到数据正在发送!");
			int bufferSize = 1024 * 10;
			byte[] buffer = new byte[bufferSize];
			int length = -1;
			/* 从文件读取数据至缓冲区 */
			while ((length = fStream.read(buffer)) != -1) {
				/* 将资料写入DataOutputStream中 */
				ds.write(buffer, 0, length);
			}
			ds.writeBytes(end);
			ds.writeBytes(twoHyphens  boundary  twoHyphens  end);
			/* close streams */
			fStream.close();
			ds.flush();
			/* 取得Response内容 */
			InputStream is = con.getInputStream();
			int ch;
			StringBuffer b = new StringBuffer();
			while ((ch = is.read()) != -1) {
				b.append((char) ch);
			}
			/* 将Response显示于Dialog */
			 showDialog("上传成功");
			/* 关闭DataOutputStream */
			ds.close();
		} catch (Exception e) {
			Log.d("OK", "jsdj");
			System.out.print("网络出现异常!");
			// showDialog("上传失败");
			e.printStackTrace();
		}
	}

	/* 显示Dialog的method */
	private void showDialog(String mess) {
		new AlertDialog.Builder(MainActivity.this).setTitle("提示").setMessage(mess).setNegativeButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
			}
		}).show();
	}

}

服务器端代码:

package com.upload.servlet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public UploadServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		RequestContext req = new ServletRequestContext(request);
		if (FileUpload.isMultipartContent(req)) {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload fileUpload = new ServletFileUpload(factory);
			fileUpload.setFileSizeMax(1024 * 1024 * 1024);

			List items = new ArrayList();
			try {
				items = fileUpload.parseRequest(request);
			} catch (Exception e) {

			}

			Iterator it = items.iterator();
			while (it.hasNext()) {
				FileItem fileItem = (FileItem) it.next();
				if (fileItem.isFormField()) {
					System.out.println(fileItem.getFieldName()  " "  fileItem.getName()  " "  new String(fileItem.getString().getBytes("ISO-8859-1"), "GBK"));
				} else {
					System.out.println(fileItem.getFieldName()  " "  fileItem.getName()  " "  fileItem.isInMemory()  " "  fileItem.getContentType()  " "  fileItem.getSize());
					if (fileItem.getName() != null && fileItem.getSize() != 0) {
						File fullFile = new File(fileItem.getName());
						File newFile = new File("F:\\upload\\"  fullFile.getName());
						try {
							fileItem.write(newFile);
						} catch (Exception E) {

						}
					} else {
						System.out.println("no file choosen or empty file");
					}
				}
			}
		}
	}

}

评论

发表评论必须先登陆, 您可以 登陆 或者 注册新账号 !


在线咨询: 问题反馈
客服QQ:174666394

有问题请留言,看到后及时答复