Android端上传图片到后台,存储到数据库中 详细代码

出门莫恨无人随,书中车马多如簇。这篇文章主要讲述Android端上传图片到后台,存储到数据库中 详细代码相关的知识,希望能为你提供帮助。
首先点击头像弹出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 voidbackgroundAlpha (float bgAlpha){ WindowManager.LayoutParams lp= getWindow().getAttributes(); lp.alpha=bgAlpha; getWindow().setAttributes(lp); }


下面为调用相机 相册时所用的方法


UrlUtil.IMG_URL为访问servlet的路径


//调用相机 private String capturPath=""; publicvoid 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.Builderalter = 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;
StringBOUNDARY =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 = https://www.songbingjia.com/android/(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的代码,
1 //从android端 上传图片 2public void uploadImg(HttpServletRequest request, HttpServletResponse response) 3throws IOException { 4String userName = request.getParameter("userName"); 5System.out.println("从Android获得的UserNAme为:"+userName); 6PrintWriter out = response.getWriter(); 7// 创建文件项目工厂对象 8DiskFileItemFactory factory = new DiskFileItemFactory(); 9// 设置文件上传路径
需要在webRoot下新建一个名为upload的文件夹,在里面再建个名为photo的文件夹
10String upload = this.getServletContext().getRealPath("upload/photo"); 11 12// 获取系统默认的临时文件保存路径,该路径为Tomcat根目录下的temp文件夹 13String temp = System.getProperty("java.io.tmpdir"); 14// 设置缓冲区大小为 5M 15factory.setSizeThreshold(1024 * 1024 * 5); 16// 设置临时文件夹为temp 17factory.setRepository(new File(temp)); 18// 用工厂实例化上传组件,ServletFileUpload 用来解析文件上传请求 19ServletFileUpload servletFileUpload = new ServletFileUpload(factory); 20String path = null; 21// 解析结果放在List中 22try { 23List< FileItem> list = servletFileUpload.parseRequest(request); 24 25for (FileItem item : list) { 26String name = item.getFieldName(); 27InputStream is = item.getInputStream(); 28 29if (name.contains("content")) { 30System.out.println(inputStream2String(is)); 31} else if (name.contains("img")) { 32try { 33path = upload+"\\"+item.getName(); 34inputStream2File(is, path); 35TestMethod tm = new TestMethod();
int c = tm.insertImages(userName, ReadPhoto(path)); 42System.out.println(c); 43break; 44} catch (Exception e) { 45e.printStackTrace(); 46} 47} 48} 49out.write(path); //这里我把服务端成功后,返回给客户端的是上传成功后路径 50} catch (FileUploadException e) { 51e.printStackTrace(); 52System.out.println("failure"); 53out.write("failure"); 54} 55 56out.flush(); 57out.close(); 58 59 60 61 62} 63// 流转化成字符串 64public static String inputStream2String(InputStream is) throws IOException { 65ByteArrayOutputStream baos = new ByteArrayOutputStream(); 66int i = -1; 67while ((i = is.read()) != -1) { 68baos.write(i); 69} 70return baos.toString(); 71} 72 73// 流转化成文件 74public static void inputStream2File(InputStream is, String savePath) throws Exception { 75System.out.println("文件保存路径为:" + savePath); 76File file = new File(savePath); 77InputStream inputSteam = is; 78BufferedInputStream fis = new BufferedInputStream(inputSteam); 79FileOutputStream fos = new FileOutputStream(file); 80int f; 81while ((f = fis.read()) != -1) { 82fos.write(f); 83} 84fos.flush(); 85fos.close(); 86fis.close(); 87inputSteam.close(); 88 89} 90public static byte[] ReadPhoto(String path) { 91File file = new File(path); 92FileInputStream fin; 93// 建一个缓冲保存数据 94ByteBuffer nbf = ByteBuffer.allocate((int) file.length()); 95byte[] array = new byte[1024]; 96int offset = 0, length = 0; 97byte[] content = null; 98try { 99fin = new FileInputStream(file); 100while((length = fin.read(array)) > 0){ 101if(length != 1024) nbf.put(array,0,length); 102else nbf.put(array); 103offset += length; 104} 105fin.close(); 106content = nbf.array(); 107} catch (FileNotFoundException e) { 108// TODO Auto-generated catch block 109e.printStackTrace(); 110} catch (IOException e) { 111// TODO Auto-generated catch block 112e.printStackTrace(); 113} 114return content; 115}

1
查询数据库update
public class TestMethod { 2public int insertImages(String desc,byte[] content) { 3Connection con = DBcon.getConnection(); 4PreparedStatement pstmt = null; 5String sql = "update user set image = ? " + 6"where userName = ? "; 7int affCount = 0; 8try { 9pstmt = con.prepareStatement(sql); 10pstmt.setBytes(1, content); 11pstmt.setString(2, desc); 12affCount = pstmt.executeUpdate(); 13} catch (SQLException e1) { 14// TODO Auto-generated catch block 15e1.printStackTrace(); 16} 17return affCount; 18} 19 }

【Android端上传图片到后台,存储到数据库中 详细代码】 







































































































    推荐阅读