Android端上傳圖片到後臺,儲存到資料庫中
阿新 • • 發佈:2019-01-10
首先點選頭像彈出popwindow,點選相簿,相機,呼叫手機自帶的裁剪功能,然後非同步任務類訪問伺服器,上傳頭像,儲存到資料庫中,
下面寫出popwindow的程式碼
//設定popwindow public PopupWindow getPopWindow(View view){ PopupWindow popupWindow=new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT,true); // popupWindow.setFocusable(true); //點選pop外面是否消失 popupWindow.setOutsideTouchable(true); anim底下的動畫效果 popupWindow.setAnimationStyle(R.style.popStyle); //設定背景透明度 backgroundAlpha(0.3f); //———————— //設定View隱藏 loginHead.setVisibility(View.GONE); popupWindow.setBackgroundDrawable(new ColorDrawable()); popupWindow.showAtLocation(loginHead, Gravity.BOTTOM, 0, 0); popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { //設定背景透明度 backgroundAlpha(1f); //設定View可見 loginHead.setVisibility(View.VISIBLE); } }); return popupWindow; } //設定透明度 public void backgroundAlpha (float bgAlpha){ WindowManager.LayoutParams lp= getWindow().getAttributes(); lp.alpha=bgAlpha; getWindow().setAttributes(lp); } //下面為呼叫相機 相簿時所用的方法 UrlUtil.IMG_URL為訪問servlet的路徑 //呼叫相機 private String capturPath=""; public void tekePhoto(){ Intent camera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File parent = FileUitlity.getInstance(getApplicationContext()) .makeDir("head_img"); capturPath=parent.getPath() +File.separatorChar +System.currentTimeMillis() +".jpg"; camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(capturPath))); camera.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); startActivityForResult(camera, 1); } /* * 呼叫相簿 * */ public void phonePhoto(){ Intent intent=new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent,2); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode != Activity.RESULT_OK){ return ; } //相機返回結果,呼叫系統裁剪 if(requestCode==1){ startPicZoom(Uri.fromFile(new File(capturPath))); } //相簿返回結果,呼叫系統裁剪 else if (requestCode==2){ Cursor cursor= getContentResolver() .query(data.getData() , new String[]{MediaStore.Images.Media.DATA} , null, null, null); cursor.moveToFirst(); capturPath=cursor.getString( cursor.getColumnIndex( MediaStore.Images.Media.DATA)); cursor.close(); startPicZoom(Uri.fromFile(new File(capturPath))); }else if(requestCode==3){ Bundle bundle= data.getExtras(); if(bundle!=null){ final Bitmap bitmap = bundle.getParcelable("data"); loginHead.setImageBitmap(bitmap); pw.dismiss(); AlertDialog.Builder alter = new AlertDialog.Builder(this) .setPositiveButton("上傳", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { 上傳時用的方法 File file = new File(capturPath); new Upload(file).execute(UrlUtil.IMG_URL+"&userName="+myAplication.getUsername()); Toast.makeText(getBaseContext(),UrlUtil.IMG_URL+"&userName="+myAplication.getUsername(),Toast.LENGTH_SHORT).show(); //String result = UploadImg.uploadFile(file, UrlUtil.IMG_URL); // Toast.makeText(getBaseContext(),result,Toast.LENGTH_SHORT).show(); /*uploadImg(bitmap);*/ } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog dialog = alter.create(); dialog.show(); } } }
下面為非同步任務類 UploadImg.uploadFile(file,strings[0]);為上傳的任務類,在非同步任務類中呼叫 public class Upload extends AsyncTask<String,Void,String> { File file; public Upload(File file){ this.file = file; } @Override protected String doInBackground(String... strings) { return UploadImg.uploadFile(file,strings[0]); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); if(s != null){ Toast.makeText(getBaseContext(),"上傳成功",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getBaseContext(),"上傳失敗",Toast.LENGTH_SHORT).show(); } } }
上傳所用的任務類 public class UploadImg { private static final String TAG = "uploadFile"; private static final int TIME_OUT = 10*1000; //超時時間 private static final String CHARSET = "utf-8"; //設定編碼 /** * android上傳檔案到伺服器 * @param file 需要上傳的檔案 * @param RequestURL 請求的rul * @return 返回響應的內容 */ public static String uploadFile(File file, String RequestURL){ String result = null; String BOUNDARY = UUID.randomUUID().toString(); //邊界標識 隨機生成 String PREFIX = "--" , LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; //內容型別 try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); conn.setDoInput(true); //允許輸入流 conn.setDoOutput(true); //允許輸出流 conn.setUseCaches(false); //不允許使用快取 conn.setRequestMethod("POST"); //請求方式 conn.setRequestProperty("Charset", CHARSET); //設定編碼 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); conn.setRequestProperty("action", "upload"); conn.connect(); if(file!=null){ /** * 當檔案不為空,把檔案包裝並且上傳 */ DataOutputStream dos = new DataOutputStream( conn.getOutputStream()); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * 這裡重點注意: * name裡面的值為伺服器端需要key 只有這個key 才可以得到對應的檔案 * filename是檔案的名字,包含字尾名的 比如:abc.png */ sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END); sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); InputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = 0; while((len=is.read(bytes))!=-1){ dos.write(bytes, 0, len); } is.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes(); dos.write(end_data); dos.flush(); /** * 獲取響應碼 200=成功 * 當響應成功,獲取響應的流 */ int res = conn.getResponseCode(); if(res==200){ InputStream input = conn.getInputStream(); StringBuffer sb1= new StringBuffer(); int ss ; while((ss=input.read())!=-1){ sb1.append((char)ss); } result = sb1.toString(); System.out.println(result); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } }
上面就是android的程式碼,下面寫出後臺servlet的程式碼
//從android端 上傳圖片
public void uploadImg(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String userName = request.getParameter("userName");
System.out.println("從Android獲得的UserNAme為:"+userName);
PrintWriter out = response.getWriter();
// 建立檔案專案工廠物件
DiskFileItemFactory factory = new DiskFileItemFactory();
// 設定檔案上傳路徑
需要在webRoot下新建一個名為upload的資料夾,在裡面再建個名為photo的資料夾
String upload = this.getServletContext().getRealPath("upload/photo");
// 獲取系統預設的臨時檔案儲存路徑,該路徑為Tomcat根目錄下的temp資料夾
String temp = System.getProperty("java.io.tmpdir");
// 設定緩衝區大小為 5M
factory.setSizeThreshold(1024 * 1024 * 5);
// 設定臨時資料夾為temp
factory.setRepository(new File(temp));
// 用工廠例項化上傳元件,ServletFileUpload 用來解析檔案上傳請求
ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
String path = null;
// 解析結果放在List中
try {
List<FileItem> list = servletFileUpload.parseRequest(request);
for (FileItem item : list) {
String name = item.getFieldName();
InputStream is = item.getInputStream();
if (name.contains("content")) {
System.out.println(inputStream2String(is));
} else if (name.contains("img")) {
try {
path = upload+"\\"+item.getName();
inputStream2File(is, path);
TestMethod tm = new TestMethod();
int c = tm.insertImages(userName, ReadPhoto(path));
System.out.println(c);
break;
} catch (Exception e) {
e.printStackTrace();
}
}
}
out.write(path); //這裡我把服務端成功後,返回給客戶端的是上傳成功後路徑
} catch (FileUploadException e) {
e.printStackTrace();
System.out.println("failure");
out.write("failure");
}
out.flush();
out.close();
}
// 流轉化成字串
public static String inputStream2String(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i = -1;
while ((i = is.read()) != -1) {
baos.write(i);
}
return baos.toString();
}
// 流轉化成檔案
public static void inputStream2File(InputStream is, String savePath) throws Exception {
System.out.println("檔案儲存路徑為:" + savePath);
File file = new File(savePath);
InputStream inputSteam = is;
BufferedInputStream fis = new BufferedInputStream(inputSteam);
FileOutputStream fos = new FileOutputStream(file);
int f;
while ((f = fis.read()) != -1) {
fos.write(f);
}
fos.flush();
fos.close();
fis.close();
inputSteam.close();
}
public static byte[] ReadPhoto(String path) {
File file = new File(path);
FileInputStream fin;
// 建一個緩衝儲存資料
ByteBuffer nbf = ByteBuffer.allocate((int) file.length());
byte[] array = new byte[1024];
int offset = 0, length = 0;
byte[] content = null;
try {
fin = new FileInputStream(file);
while((length = fin.read(array)) > 0){
if(length != 1024) nbf.put(array,0,length);
else nbf.put(array);
offset += length;
}
fin.close();
content = nbf.array();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return content;
}
查詢資料庫update
public class TestMethod {
public int insertImages(String desc,byte[] content) {
Connection con = DBcon.getConnection();
PreparedStatement pstmt = null;
String sql = "update user set image = ? " +
"where userName = ? ";
int affCount = 0;
try {
pstmt = con.prepareStatement(sql);
pstmt.setBytes(1, content);
pstmt.setString(2, desc);
affCount = pstmt.executeUpdate();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return affCount;
}
}