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();
}
}
延伸:
之前做上傳圖片是採用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。希望對大家有所幫助!
相關文章
- Android圖片Base64加密+文字上傳Android加密
- uniapp uview 上傳圖片,資料以formData + File 形式傳輸APPViewORM
- JS base64 圖片上傳JS
- 上傳圖片生成base64
- java,springboot + thymeleaf 上傳圖片、刪除圖片到伺服器、本地,壓縮圖片上傳(有些圖片會失真),原圖上傳JavaSpring Boot伺服器
- 日常筆記三:將base64的圖片上傳到本地筆記
- Java實現圖片上傳到伺服器,並把上傳的圖片讀取出來Java伺服器
- 通過API介面實現圖片上傳API
- ci框架中的圖片上傳框架
- Android圖片上傳到阿里雲OSS小案例Android阿里
- 拖拽上傳如何獲取到圖片的base64
- VueQuillEditor富文字上傳圖片-非base64VueUI
- element上傳圖片元件使用方法|圖片回顯|格式轉換base64元件
- Android本地圖片上傳(拍照+相簿)Android地圖
- AntD框架的upload元件上傳圖片時使用customRequest方法自定義上傳行為框架元件
- Laravel 使用 FastDFS 上傳圖片LaravelAST
- 線上直播原始碼,js 檔案上傳 圖片上傳 傳輸速度計算原始碼JS
- 上傳圖片
- Java傳輸檔案使用Base64優化傳輸速率。Java優化
- react ts 使用七牛 傳輸圖片React
- angular上傳圖片到.netcore後端AngularNetCore後端
- Laravel 上傳圖片到七牛雲Laravel
- vue 圖片上傳到阿里雲ossVue阿里
- Flutter 上傳圖片到阿里雲OSSFlutter阿里
- TCP/IP 通訊傳輸流TCP
- [BUG反饋]使用base64上傳圖片,php://input裡沒有值PHP
- 知識點系列一---上傳圖片並通過canvas展示Canvas
- markdown編輯器typora本地圖片上傳到自己的伺服器地圖伺服器
- Element-UI框架 —— Upload 上傳(圖片上傳格式和大小判斷)UI框架
- MultipartFile上傳圖片儲存伺服器伺服器
- PHP CURL 上傳二進位制流圖片PHP
- 網路中的圖片傳輸
- electron上傳圖片
- 上傳圖片jsJS
- 裁剪上傳圖片
- Azure DevOps (七) 通過SSH部署上傳到伺服器的應用dev伺服器
- vue+element 將圖片壓縮並轉換成base64上傳圖片Vue
- python使用MQTT給硬體傳輸圖片PythonMQQT
- cropper,圖片剪輯上傳工具的使用