android上传图片到服务器(使用base64字节流的形式通过 AsyncHttpClient框架传输)

简介:

转自:http://blog.csdn.net/wolaizhaomengxiang/article/details/22721779

AsyncHttpClient  是一个框架提供的库  可以异步传输,使用时需下载android-async-http-1.4.4.jar包导入到项目中

下载地址:http://loopj.com/android-async-http

public static void reg(final Context cont,Bitmap photodata,String regData) {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			
			//将bitmap一字节流输出 Bitmap.CompressFormat.PNG 压缩格式,100:压缩率,baos:字节流
			photodata.compress(Bitmap.CompressFormat.PNG, 100, baos);
			baos.close();
			byte[] buffer = baos.toByteArray();
			System.out.println("图片的大小:"+buffer.length);
			
			//将图片的字节流数据加密成base64字符输出
			String photo = Base64.encodeToString(buffer, 0, buffer.length,Base64.DEFAULT);

			//photo=URLEncoder.encode(photo,"UTF-8");
			RequestParams params = new RequestParams();
           	        params.put("photo", photo);
                        params.put("name", "woshishishi");//传输的字符数据
                        String url = "http://10.0.2.2:8080/IC_Server/servlet/RegisterServlet1";
 
            
                        AsyncHttpClient client = new AsyncHttpClient();
                        client.post(url, params, new AsyncHttpResponseHandler() {
            	    	@Override  
                	public void onSuccess(int statusCode, String content){  
            		Toast.makeText(cont, "头像上传成功!"+content, 0)
                   	 .show(); 
               			 }  
                	@Override  
                	public void onFailure(Throwable e, String data){  
                	Toast.makeText(cont, "头像上传失败!", 0)
                    	.show(); 
                }
            });
 
        } catch (Exception e) {
            e.printStackTrace();
        }

	}

服务器中 serverlet中的代码:

package uestc.app.ic.server.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

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

import sun.misc.BASE64Decoder;

public class RegisterServlet1 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		String photo = request.getParameter("photo");
		String name = request.getParameter("name");

		try {

			// 对base64数据进行解码 生成 字节数组,不能直接用Base64.decode();进行解密
			byte[] photoimg = new BASE64Decoder().decodeBuffer(photo);
			for (int i = 0; i < photoimg.length; ++i) {
				if (photoimg[i] < 0) {
					// 调整异常数据
					photoimg[i] += 256;
				}
			}

			// byte[] photoimg = Base64.decode(photo);//此处不能用Base64.decode()方法解密,我调试时用此方法每次解密出的数据都比原数据大  所以用上面的函数进行解密,在网上直接拷贝的,花了好几个小时才找到这个错误(菜鸟不容易啊)
			System.out.println("图片的大小:" + photoimg.length);
			File file = new File("e:", "decode.png");
			File filename = new File("e:\\name.txt");
			if (!filename.exists()) {
				file.createNewFile();
			}
			if (!file.exists()) {
				file.createNewFile();
			}
			FileOutputStream out = new FileOutputStream(file);
			FileOutputStream out1 = new FileOutputStream(filename);
			out1.write(name.getBytes());
			out.write(photoimg);
			out.flush();
			out.close();
			out1.flush();
			out1.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}


延伸:

Android 通过Base64上传图片到服务器

之前做上传图片是采用HttpServlet上传,不过用了一下Base64上传图片后,感觉比HttpServlet方便很多,大家也可以跟着尝试一下。


前台图片处理:(传Bitmap对象即可)

	/**
	 * 通过Base32将Bitmap转换成Base64字符串
	 * @param bit
	 * @return
	 */
	public String Bitmap2StrByBase64(Bitmap bit){
	   ByteArrayOutputStream bos=new ByteArrayOutputStream();
	   bit.compress(CompressFormat.JPEG, 40, bos);//参数100表示不压缩
	   byte[] bytes=bos.toByteArray();
	   return Base64.encodeToString(bytes, Base64.DEFAULT);
	}

前台发送数据:(調用 setImgByStr()方法,第一個參數imgStr 为Bitmap转成Base64的字符串,第二个参数imgName为图片的名字,包含后缀名.jpg

	public static String host = "http://192.168.1.166:8080/ImageServer/";
	
	public static String getContent(String url) throws Exception {

		StringBuilder sb = new StringBuilder();
 
		HttpClient client = new DefaultHttpClient();
		HttpParams httpParams = client.getParams();
		// 设置网络超时参数
		HttpConnectionParams.setConnectionTimeout(httpParams, 3000);

		HttpConnectionParams.setSoTimeout(httpParams, 5000);
		HttpResponse response = client.execute(new HttpGet(url));
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					entity.getContent(), "UTF-8"), 8192);

			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			reader.close();

		}

		return sb.toString();
	}
	public static HttpResponse post(Map<String, Object> params, String url) {

		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("charset", HTTP.UTF_8);
		httpPost.setHeader("Content-Type",
				"application/x-www-form-urlencoded; charset=utf-8");
		HttpResponse response = null;
		if (params != null && params.size() > 0) {
			List<NameValuePair> nameValuepairs = new ArrayList<NameValuePair>();
			for (String key : params.keySet()) {
				nameValuepairs.add(new BasicNameValuePair(key, (String) params
						.get(key)));
			}
			try {
				httpPost.setEntity(new UrlEncodedFormEntity(nameValuepairs,
						HTTP.UTF_8));
				response = client.execute(httpPost);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (RuntimeException e) {
				e.printStackTrace();
			}
		} else {
			try {
				response = client.execute(httpPost);
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return response;

	}
	public static Object getValues(Map<String, Object> params, String url) {
		String token = "";
		HttpResponse response = post(params, url);
		if (response != null) {
			try {
				token = EntityUtils.toString(response.getEntity());
				response.removeHeaders("operator");
			} catch (ParseException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return token;
	}
	public static Object setImgByStr(String imgStr,String imgName){
		String url =  host+"channel-uploadImage.action";
		Map<String,Object> params = new HashMap<String, Object>();
		params.put("imgStr", imgStr);
		params.put("imgName", imgName);
		return getValues(params, url);
	}

后台接收数据:

	public void uploadPhoto() {
		//获取存储路径
		HttpServletRequest request = ServletActionContext.getRequest();
		String path = ServletActionContext.getServletContext().getRealPath("/")+"upload";
		File file = new File(path);
		if(!file.exists()){
			file.mkdir();
		}
		String imgPath  = path + request.getParameter("imgName");
		String imgStr = request.getParameter("imgStr");
		boolean flag = string2Image(imgStr, imgPath);
		JacksonUtil.responseJSON(response, flag);
	}

后台图片处理:

	/**
	 * 通过BASE64Decoder解码,并生成图片
	 * @param imgStr 解码后的string
	 */
	public boolean string2Image(String imgStr, String imgFilePath) {
		// 对字节数组字符串进行Base64解码并生成图片
		if (imgStr == null)
			return false;
		try {
			// Base64解码
			byte[] b = new BASE64Decoder().decodeBuffer(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					// 调整异常数据
					b[i] += 256;
				}
			}
			// 生成Jpeg图片
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(b);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}	

OK ! 如果成功上传前端会接收到true ,反之失败false。希望对大家有所帮助!

相关文章
|
1月前
|
Ubuntu 网络协议 Java
【Android平板编程】远程Ubuntu服务器code-server编程写代码
【Android平板编程】远程Ubuntu服务器code-server编程写代码
|
1月前
|
Ubuntu 网络协议 Java
在Android平板上使用code-server公网远程Ubuntu服务器编程
在Android平板上使用code-server公网远程Ubuntu服务器编程
|
2月前
|
移动开发 算法 安全
安卓逆向 -- 算法基础(Base64与HEX)
安卓逆向 -- 算法基础(Base64与HEX)
13 1
|
2月前
|
Ubuntu 网络协议 Linux
【Linux】Android平板上远程连接Ubuntu服务器code-server进行代码开发
【Linux】Android平板上远程连接Ubuntu服务器code-server进行代码开发
48 0
|
3月前
|
数据采集 编解码 图形学
Android平台Unity下如何通过WebCamTexture采集摄像头数据并推送至RTMP服务器或轻量级RTSP服务
Android平台Unity下如何通过WebCamTexture采集摄像头数据并推送至RTMP服务器或轻量级RTSP服务
|
3月前
|
安全 网络协议 Linux
【公网远程手机Android服务器】安卓Termux搭建Web服务器
【公网远程手机Android服务器】安卓Termux搭建Web服务器
58 0
|
4月前
|
缓存 JSON Android开发
[Android]网络框架之OkHttp(详细)(kotlin)
[Android]网络框架之OkHttp(详细)(kotlin)
139 0
|
4月前
|
XML JSON Apache
【Android】如何获得Apache服务器的JSON文件数据
【Android】如何获得Apache服务器的JSON文件数据
56 0
|
20天前
|
Java Android开发
Android 开发获取通知栏权限时会出现两个应用图标
Android 开发获取通知栏权限时会出现两个应用图标
12 0
|
1月前
|
XML 缓存 Android开发
Android开发,使用kotlin学习多媒体功能(详细)
Android开发,使用kotlin学习多媒体功能(详细)
94 0