前端 andoid activity用到的函數
AsyncHttpClient 是一個框架提供的庫 能夠異步傳輸,使用時需下載android-async-http-1.4.4.jar包導入到項目中
- 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();
- }