序言:之前我們講解了一些簡(jiǎn)單后端開發(fā)的工具和基礎(chǔ),如果你還沒有了解的話,請(qǐng)移步:
工?具?介?紹?:android開發(fā)怎么少的了后端(上)
簡(jiǎn)單接口介紹:android開發(fā)怎么少的了后端(中)
之前咱們講了如何請(qǐng)求服務(wù)器,以及像數(shù)據(jù)庫(kù)中存簡(jiǎn)單的數(shù)據(jù),但是我們大家都知道,一個(gè)app中不可能只有文字的,還要有圖片等一系列復(fù)雜數(shù)據(jù)。好了,今天咱們來(lái)講一下如何上傳圖片到咱們的服務(wù)器呢?數(shù)據(jù)庫(kù)該怎么存呢?
圖片你可以作為文件上傳,也可以作為流上傳,還可以作為base64編碼上傳。在這里我們使用簡(jiǎn)單一點(diǎn)的操作,使用base64編碼上傳,簡(jiǎn)單說(shuō)一下,就是將我們的圖片轉(zhuǎn)化為base64編碼進(jìn)行上傳,保存的格式是字符類型。好了,話也不多說(shuō),直接看一個(gè)例子,還是注冊(cè),只不過(guò)注冊(cè)的時(shí)候得加上頭像:
1. 首先新建一個(gè)Servlet,作為圖片上傳的servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Content-Type", "text/html;charset=UTF-8"); //設(shè)置頭部的編碼,防止中文亂碼
String username = request.getParameter("username");
String password = request.getParameter("password");
String userhead = request.getParameter("userhead");
// 判空
if (username == null || username.equals("") || password == null || password.equals("") || userhead == null
|| userhead.equals("")) {
return;
}
// 請(qǐng)求數(shù)據(jù)庫(kù)
DBUtils dbUtils = new DBUtils();
dbUtils.openConnect();
BaseBean bean = new BaseBean();
RegisterBean data = new RegisterBean();
String imageName = TimeUtils.getNowTime() + ".jpg"; // 以當(dāng)前時(shí)間作為圖片名,具有唯一性
System.out.println(getServletContext().getRealPath("/images"));
String path = getServletContext().getRealPath("/images/" + imageName); // 圖片的絕對(duì)路徑(保存在apache服務(wù)器的某個(gè)文件夾目錄下)
if (!Base64Utils.GenerateImage(userhead, path)) { // 判斷圖片是否保存成功
bean.setCode(-2);
bean.setData(data);
bean.setMsg("圖片出錯(cuò)?。?);
} else if (dbUtils.isExistInDB(username)) {
bean.setCode(-1);
bean.setData(data);
bean.setMsg("該賬號(hào)已存在");
} else if (!dbUtils.insertDataToDB(username, password, imageName)) { //判斷注冊(cè)是否成功
bean.setCode(0);
bean.setMsg("注冊(cè)成功?。?);
data.setUsername(username);
data.setPassword(password);
data.setToken(TokenUtils.getToken(username, password));
bean.setData(data);
} else {
bean.setCode(500);
bean.setData(data);
bean.setMsg("數(shù)據(jù)庫(kù)錯(cuò)誤");
}
Gson gson = new Gson();
String json = gson.toJson(bean);
try {
response.getWriter().println(json);// 將json數(shù)據(jù)傳給客戶端
} catch (Exception e) {
e.printStackTrace();
} finally {
response.getWriter().close(); // 關(guān)閉這個(gè)流,不然會(huì)發(fā)生錯(cuò)誤的
}
dbUtils.closeConnect(); // 關(guān)閉數(shù)據(jù)庫(kù)連接
}
稍微解釋一下:
這里我們是在客戶端將圖片轉(zhuǎn)成base64編碼,然后在服務(wù)器端將編碼又轉(zhuǎn)成圖片,保存在服務(wù)器的某個(gè)文件夾下(可以自己定制,但是得要在該工程下的某個(gè)文件夾下,這里可以用getServletContext().getRealPath()獲得,然后將圖片的名字和服務(wù)器的地址進(jìn)行拼接,將這個(gè)最終的地址保存到數(shù)據(jù)庫(kù)中就好了,可能有人要問(wèn)了,為什么不直接將圖片存到數(shù)據(jù)庫(kù)中呢?這個(gè)可以是可以,但是數(shù)據(jù)庫(kù)存取的大小是有限度的,如果直接存數(shù)據(jù)庫(kù)的話可能會(huì)導(dǎo)致圖片出錯(cuò),數(shù)據(jù)庫(kù)也會(huì)崩掉。
DBUtils的代碼:
public boolean insertDataToDB(String username, String password, String userhead) {
String token = TokenUtils.getToken(username, password); //token可以自己按照自己的意愿生成一下
System.out.println("path------->" + userhead);
String imagePath = "http://192.168.1.101:8080/MyWeb/images/" + userhead; //這里做了一個(gè)地址拼接的過(guò)程,將這個(gè)圖片最終的地址保存到數(shù)據(jù)庫(kù)
try {
sta = conn.createStatement();
String sql = " insert into userinfo ( user_name , user_pwd , token , user_head ) values ( " + "'" + username
+ "', " + "'" + password + "', " + "'" + token + "', " + "'" + imagePath + "' )";
return sta.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
然后再奉上base64的編碼解碼代碼:
/**
* bitmap轉(zhuǎn)base64(客戶端用)
*
* @param bitmap
* @return
*/
public static String bitmapToBase64(Bitmap bitmap) {
String result = null;
ByteArrayOutputStream baos = null;
try {
if (bitmap != null) {
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
baos.flush();
baos.close();
byte[] bitmapBytes = baos.toByteArray();
result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.flush();
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 對(duì)字節(jié)數(shù)組字符串進(jìn)行Base64解碼并生成圖片(服務(wù)端用)
*
* @param imgStr
* @param imgFilePath
* @return
*/
public static boolean GenerateImage(String imgStr, String imgFilePath) {
if (imgStr == null) // 圖像數(shù)據(jù)為空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解碼
byte[] bytes = decoder.decodeBuffer(imgStr);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 調(diào)整異常數(shù)據(jù)
bytes[i] += 256;
}
}
// 生成jpeg圖片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
這么一個(gè)簡(jiǎn)單的服務(wù)端就寫好了,然后我們?nèi)タ蛻舳藱z測(cè)一把,布局神馬的咱們就簡(jiǎn)單一點(diǎn)好了:

請(qǐng)求的話,還是上次演示的asynchttpclient:
public void requestHost(){
if (CygStringUtil.isEmpty(CygStringUtil.getEditTextContent(arEtUsername), CygStringUtil.getEditTextContent(arEtPassword), image)) {
CygToast.showToast("不能為空!!!");
return;
}
pd.setTitle("上傳圖片");
pd.setMessage("正在火速上傳,請(qǐng)稍后....");
pd.setCanceledOnTouchOutside(false);
pd.show();
String url = "http://192.168.1.101:8080/MyWeb/UploadServlet";
RequestParams params = new RequestParams();
params.put("username", arEtUsername.getText().toString());
params.put("password", arEtPassword.getText().toString());
Log.d(TAG,"userhead=====" + image);
params.put("userhead", image);
RequestUtils.ClientPost(url, params, new NetCallBack() {
@Override
public void onMySuccess(byte[] response) {
Log.d(TAG,"upload picture success---->" + new String(response));
Toast.makeText(this,"json=" + new String(response),Toast.LENGTH_SHORT).show();
pd.dismiss();
}
@Override
public void onMyFailure(byte[] response, Throwable throwable) {
pd.dismiss();
Log.e(TAG,new String(response)+"\n"+ throwable.toString());
}
});
}
這樣一個(gè)簡(jiǎn)單的請(qǐng)求就寫好了,咱們來(lái)看一下效果:

這里顯示的是注冊(cè)成功了,然后我們?nèi)タ纯捶?wù)器的某個(gè)文件夾下有沒有呢?

好,服務(wù)器中也有了,然后我們?nèi)?shù)據(jù)庫(kù)中看看,有沒有剛剛那條數(shù)據(jù)呢?

咦?。?!怎么數(shù)據(jù)庫(kù)中是空的呢???仔細(xì)想想,服務(wù)器中都有了,數(shù)據(jù)庫(kù)中沒有,那肯定存儲(chǔ)的過(guò)程中發(fā)生了錯(cuò)誤,好,去看看服務(wù)端,果然報(bào)錯(cuò):

這是報(bào)我們上傳的圖片編碼太長(zhǎng)了,數(shù)據(jù)庫(kù)之前設(shè)定的長(zhǎng)度不夠,這就明白了,那咱就把數(shù)據(jù)庫(kù)中這個(gè)字段改一下唄,之前是varchar(45)的,現(xiàn)在咱們改成varchar(100)試試,然后咱們把服務(wù)器的圖片清空,重新上傳一遍,這回成功了:

好了,咱們的圖片上傳就到此了,心動(dòng)的話就趕緊的試試吧?。?!
