android 上传Bitmap到服务器端

时间:2022-08-28 19:06:42

Android拍照获取照片路径并上传至服务器+Servlet代码


摘要: 拍照和选择本地图片上传的代码网上很多,但也有的代码在自己程序上跑不起来,所以整的有点尴尬,今天自己的拍照上传和本地图片选择上传代码都已完成。

先来客户端代码【这里只写了主要代码】

先来张效果图,

android 上传Bitmap到服务器端


 
  
iv_photo.setOnClickListener(new OnClickListener() {		@Override		public void onClick(View v) {			new ActionSheetDialog(SendGoodsDetailsActivity.this).builder().setTitle("上传车辆照片")						.setCancelable(false).setCanceledOnTouchOutside(false)						.addSheetItem("拍照上传", SheetItemColor.Blue, new OnSheetItemClickListener() {				@Override				public void onClick(int which) {					// 拍照					//设置图片的保存路径,作为全局变量					imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/filename.jpg";					File temp = new File(imageFilePath);							Uri imageFileUri = Uri.fromFile(temp);//获取文件的Uri	 					Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//跳转到相机Activity					it.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);//告诉相机拍摄完毕输出图片到指定的Uri					 startActivityForResult(it, 102);				}				}).addSheetItem("相册选择", SheetItemColor.Blue, new OnSheetItemClickListener() {				@Override				public void onClick(int which) {					// 相册选取					Intent intent1 = new Intent(Intent.ACTION_GET_CONTENT);					intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");					startActivityForResult(intent1, 103);						}					}).show();				}			});@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) {		switch(requestCode){		 case 102:			 if (resultCode == Activity.RESULT_OK) {				 				 Bitmap bmp = BitmapFactory.decodeFile(imageFilePath);  		                iv_photo.setImageBitmap(bmp);			 }		 break;		 case 103:			 Bitmap bm = null;			 // 外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口			 ContentResolver resolver = getContentResolver();			 try {				Uri originalUri = data.getData(); // 获得图片的uri				bm = MediaStore.Images.Media.getBitmap(resolver, originalUri); // 显得到bitmap图片				// 这里开始的第二部分,获取图片的路径:				String[] proj = { MediaStore.Images.Media.DATA };				// 好像是android多媒体数据库的封装接口,具体的看Android文档				@SuppressWarnings("deprecation")				Cursor cursor = managedQuery(originalUri, proj, null, null, null);				// 按我个人理解 这个是获得用户选择的图片的索引值				int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);				// 将光标移至开头 ,这个很重要,不小心很容易引起越界				cursor.moveToFirst();				// 最后根据索引值获取图片路径				String path = cursor.getString(column_index);				iv_photo.setImageURI(originalUri);							 } catch (IOException e) {				e.printStackTrace();			 }			 break;		 }		super.onActivityResult(requestCode,resultCode,data);}下面是上传的一个工具类,嘻嘻,从网上找的一个大神的,可以用/** *  * 上传工具类 * @author spring sky * Email:vipa1888@163.com * QQ:840950105 * MyName:石明政 */public class UploadUtil {    private static final String TAG = "uploadFile";    private static final int TIME_OUT = 10*1000;   //超时时间    private static final String CHARSET = "utf-8"; //设置编码    /**     * android上传文件到服务器     * @param file  需要上传的文件     * @param RequestURL  请求的rul     * @return  返回响应的内容     */    public static String uploadFile(File file,String RequestURL){        String result = null;        String  BOUNDARY =  UUID.randomUUID().toString();  //边界标识   随机生成        String PREFIX = "--" , LINE_END = "\r\n";         String CONTENT_TYPE = "multipart/form-data";   //内容类型                try {            URL url = new URL(RequestURL);            HttpURLConnection conn = (HttpURLConnection) url.openConnection();            conn.setReadTimeout(TIME_OUT);            conn.setConnectTimeout(TIME_OUT);            conn.setDoInput(true);  //允许输入流            conn.setDoOutput(true); //允许输出流            conn.setUseCaches(false);  //不允许使用缓存            conn.setRequestMethod("POST");  //请求方式            conn.setRequestProperty("Charset", CHARSET);  //设置编码            conn.setRequestProperty("connection", "keep-alive");               conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);             conn.connect();                        if(file!=null){                /**                 * 当文件不为空,把文件包装并且上传                 */                DataOutputStream dos = new DataOutputStream( conn.getOutputStream());                StringBuffer sb = new StringBuffer();                sb.append(PREFIX);                sb.append(BOUNDARY);                sb.append(LINE_END);                /**                 * 这里重点注意:                 * name里面的值为服务器端需要key   只有这个key 才可以得到对应的文件                 * filename是文件的名字,包含后缀名的   比如:abc.png                   */                                sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END);                 sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END);                sb.append(LINE_END);                dos.write(sb.toString().getBytes());                InputStream is = new FileInputStream(file);                byte[] bytes = new byte[1024];                int len = 0;                while((len=is.read(bytes))!=-1){                    dos.write(bytes, 0, len);                }                is.close();                dos.write(LINE_END.getBytes());                byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();                dos.write(end_data);                dos.flush();                /**                 * 获取响应码  200=成功                 * 当响应成功,获取响应的流                   */                int res = conn.getResponseCode();  	            if(res==200){                    InputStream input =  conn.getInputStream();                    StringBuffer sb1= new StringBuffer();                    int ss ;                    while((ss=input.read())!=-1){                        sb1.append((char)ss);                    }                    result = sb1.toString();                    System.out.println(result);	            }            }        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return result;    }}在下就是调用上传的方法了,这里我给摘出来了File file = new File(path); //这里的path就是那个地址的全局变量							String result = UploadUtil.uploadFile(file, RequestURL);这里客户端就完成了,下面就是服务端代码,这里我用的是servletpublic class UploadShipServlet extends HttpServlet {	private static final long serialVersionUID = 1L;	private String path;	public UploadShipServlet() {		super();	}	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		this.doPost(request, response);	}	protected void doPost(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {		response.setContentType("text/html;charset=utf-8");		request.setCharacterEncoding("utf-8");		response.setCharacterEncoding("utf-8");		PrintWriter out = response.getWriter();				// 创建文件项目工厂对象		DiskFileItemFactory factory = new DiskFileItemFactory();		// 设置文件上传路径		String upload = this.getServletContext().getRealPath("/");				// 获取系统默认的临时文件保存路径,该路径为Tomcat根目录下的temp文件夹		String temp = System.getProperty("java.io.tmpdir");		// 设置缓冲区大小为 5M		factory.setSizeThreshold(1024 * 1024 * 5);		// 设置临时文件夹为temp		factory.setRepository(new File(temp));		// 用工厂实例化上传组件,ServletFileUpload 用来解析文件上传请求		ServletFileUpload servletFileUpload = new ServletFileUpload(factory);		// 解析结果放在List中		try {			List<FileItem> list = servletFileUpload.parseRequest(request);			for (FileItem item : list) {				String name = item.getFieldName();				InputStream is = item.getInputStream();				if (name.contains("content")) {					System.out.println(inputStream2String(is));				} else if (name.contains("img")) {					try {						path = upload+"\\"+item.getName();						inputStream2File(is, path);						break;					} catch (Exception e) {						e.printStackTrace();					}				}			}			out.write(path);  //这里我把服务端成功后,返回给客户端的是上传成功后路径		} catch (FileUploadException e) {			e.printStackTrace();			System.out.println("failure");			out.write("failure");		}		out.flush();		out.close();	}	// 流转化成字符串	public static String inputStream2String(InputStream is) throws IOException {		ByteArrayOutputStream baos = new ByteArrayOutputStream();		int i = -1;		while ((i = is.read()) != -1) {			baos.write(i);		}		return baos.toString();	}	// 流转化成文件	public static void inputStream2File(InputStream is, String savePath) throws Exception {		System.out.println("文件保存路径为:" + savePath);		File file = new File(savePath);		InputStream inputSteam = is;		BufferedInputStream fis = new BufferedInputStream(inputSteam);		FileOutputStream fos = new FileOutputStream(file);		int f;		while ((f = fis.read()) != -1) {			fos.write(f);		}		fos.flush();		fos.close();		fis.close();		inputSteam.close();	}}


ok了,这样就大功告成了,多整理以后好用得着。

======================================================================================

Last week, I faced a problem to send an image to the server, I have tried a lot of ways, but seemed that nothing would work.

After some research, I found the HTTPClient API , this API helped me to do the dirty work, and it did pretty well. I will show you now, how to upload images and/or strings to the web server.

It’s pretty simple, actually. I gonna do in only one function!

 

  1. // create a bitmap variable before anything;  
  2.   
  3. private Bitmap bitmap;  
  4.   
  5. // variable to set a name to the image into SD card;  
  6. // this variable, you have to put the path for the File, It's up to you;  
  7.   
  8. public static String exsistingFileName;  
  9.   
  10. // sendData is the function name, to call it, you can use something like sendData(null);  
  11. // remember to wrap it into a try catch;  
  12.   
  13. public void sendData(String[] args) throws Exception {  
  14.     try {  
  15.   
  16.         HttpClient httpClient = new DefaultHttpClient();  
  17.         HttpContext localContext = new BasicHttpContext();  
  18.   
  19.         // here, change it to your php;  
  20.   
  21.         HttpPost httpPost = new HttpPost("http://www.myURL.com/myPHP.php");  
  22.         MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
  23.         bitmap = BitmapFactory.decodeFile(exsistingFileName);  
  24.   
  25.         // you can change the format of you image compressed for what do you want;  
  26.         //now it is set up to 640 x 480;  
  27.   
  28.         Bitmap bmpCompressed = Bitmap.createScaledBitmap(bitmap, 640480true);  
  29.         ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  30.   
  31.         // CompressFormat set up to JPG, you can change to PNG or whatever you want;  
  32.   
  33.         bmpCompressed.compress(CompressFormat.JPEG, 100, bos);  
  34.         byte[] data = bos.toByteArray();  
  35.   
  36.         // sending a String param;  
  37.   
  38.         entity.addPart("myParam"new StringBody("my value"));  
  39.   
  40.         // sending a Image;  
  41.         // note here, that you can send more than one image, just add another param, same rule to the String;  
  42.   
  43.         entity.addPart("myImage"new ByteArrayBody(data, "temp.jpg"));  
  44.   
  45.         httpPost.setEntity(entity);  
  46.         HttpResponse response = httpClient.execute(httpPost, localContext);  
  47.         BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent(), "UTF-8"));  
  48.         String sResponse = reader.readLine();  
  49.   
  50.     } catch (Exception e) {  
  51.   
  52.         Log.v("myApp""Some error came up");  
  53.   
  54.     }  
  55.   
  56. }