android上傳圖片到伺服器(使用base64位元組流的形式通過 AsyncHttpClient框架傳輸)

一葉飄舟發表於2016-01-15

轉自: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。希望對大家有所幫助!

相關文章