<output id="qn6qe"></output>

    1. <output id="qn6qe"><tt id="qn6qe"></tt></output>
    2. <strike id="qn6qe"></strike>

      亚洲 日本 欧洲 欧美 视频,日韩中文字幕有码av,一本一道av中文字幕无码,国产线播放免费人成视频播放,人妻少妇偷人无码视频,日夜啪啪一区二区三区,国产尤物精品自在拍视频首页,久热这里只有精品12

      Android端上傳圖片到后臺,存儲到數(shù)據(jù)庫中 詳細(xì)代碼

      首先點擊頭像彈出popwindow,點擊相冊,相機,調(diào)用手機自帶的裁剪功能,然后異步任務(wù)類訪問服務(wù)器,上傳頭像,保存到數(shù)據(jù)庫中,

      下面寫出popwindow的代碼 

       //設(shè)置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);
              //設(shè)置背景透明度
              backgroundAlpha(0.3f);
              //————————
              //設(shè)置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() {
                      //設(shè)置背景透明度
                      backgroundAlpha(1f);
                      //設(shè)置View可見
                      loginHead.setVisibility(View.VISIBLE);
                  }
              });
              return popupWindow;
          }
          //設(shè)置透明度
          public void  backgroundAlpha (float bgAlpha){
              WindowManager.LayoutParams lp=
                      getWindow().getAttributes();
              lp.alpha=bgAlpha;
              getWindow().setAttributes(lp);
          }


      下面為調(diào)用相機 相冊時所用的方法
      
      
      UrlUtil.IMG_URL為訪問servlet的路徑

      //
      調(diào)用相機 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); } /* * 調(diào)用圖庫 * */ 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 ; } //相機返回結(jié)果,調(diào)用系統(tǒng)裁剪 if(requestCode==1){ startPicZoom(Uri.fromFile(new File(capturPath))); } //相冊返回結(jié)果,調(diào)用系統(tǒng)裁剪 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(); } } }
       

      下面為異步任務(wù)類
       UploadImg.uploadFile(file,strings[0]);為上傳的任務(wù)類,在異步任務(wù)類中調(diào)用

      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(); } } }
      上傳所用的任務(wù)類
      public class UploadImg {
      private static final String TAG = "uploadFile";
      private static final int TIME_OUT = 10*1000; //超時時間
      private static final String CHARSET = "utf-8"; //設(shè)置編碼
      /**
      * android上傳文件到服務(wù)器
      * @param file 需要上傳的文件
      * @param RequestURL 請求的rul
      * @return 返回響應(yīng)的內(nèi)容
      */
      public static String uploadFile(File file, String RequestURL){
      String result = null;
      String BOUNDARY = UUID.randomUUID().toString(); //邊界標(biāo)識 隨機生成
      String PREFIX = "--" , LINE_END = "\r\n";
      String CONTENT_TYPE = "multipart/form-data"; //內(nèi)容類型

      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); //設(shè)置編碼
      conn.setRequestProperty("connection", "keep-alive");
      conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
      conn.setRequestProperty("action", "upload");
      conn.connect();

      if(file!=null){
      /**
      * 當(dāng)文件不為空,把文件包裝并且上傳
      */
      DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
      StringBuffer sb = new StringBuffer();
      sb.append(PREFIX);
      sb.append(BOUNDARY);
      sb.append(LINE_END);
      /**
      * 這里重點注意:
      * name里面的值為服務(wù)器端需要key 只有這個key 才可以得到對應(yīng)的文件
      * 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();
      /**
      * 獲取響應(yīng)碼 200=成功
      * 當(dāng)響應(yīng)成功,獲取響應(yīng)的流
      */
      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端 上傳圖片
        2         public void uploadImg(HttpServletRequest request, HttpServletResponse response)
        3                 throws IOException {
        4             String userName = request.getParameter("userName");
        5             System.out.println("從Android獲得的UserNAme為:"+userName);
        6             PrintWriter out = response.getWriter();
        7             // 創(chuàng)建文件項目工廠對象
        8             DiskFileItemFactory factory = new DiskFileItemFactory();
        9             // 設(shè)置文件上傳路徑
      需要在webRoot下新建一個名為upload的文件夾,在里面再建個名為photo的文件夾
      10 String upload = this.getServletContext().getRealPath("upload/photo"); 11 12 // 獲取系統(tǒng)默認(rèn)的臨時文件保存路徑,該路徑為Tomcat根目錄下的temp文件夾 13 String temp = System.getProperty("java.io.tmpdir"); 14 // 設(shè)置緩沖區(qū)大小為 5M 15 factory.setSizeThreshold(1024 * 1024 * 5); 16 // 設(shè)置臨時文件夾為temp 17 factory.setRepository(new File(temp)); 18 // 用工廠實例化上傳組件,ServletFileUpload 用來解析文件上傳請求 19 ServletFileUpload servletFileUpload = new ServletFileUpload(factory); 20 String path = null; 21 // 解析結(jié)果放在List中 22 try { 23 List<FileItem> list = servletFileUpload.parseRequest(request); 24 25 for (FileItem item : list) { 26 String name = item.getFieldName(); 27 InputStream is = item.getInputStream(); 28 29 if (name.contains("content")) { 30 System.out.println(inputStream2String(is)); 31 } else if (name.contains("img")) { 32 try { 33 path = upload+"\\"+item.getName(); 34 inputStream2File(is, path); 35 TestMethod tm = new TestMethod();
      int c = tm.insertImages(userName, ReadPhoto(path)); 42 System.out.println(c); 43 break; 44 } catch (Exception e) { 45 e.printStackTrace(); 46 } 47 } 48 } 49 out.write(path); //這里我把服務(wù)端成功后,返回給客戶端的是上傳成功后路徑 50 } catch (FileUploadException e) { 51 e.printStackTrace(); 52 System.out.println("failure"); 53 out.write("failure"); 54 } 55 56 out.flush(); 57 out.close(); 58 59 60 61 62 } 63 // 流轉(zhuǎn)化成字符串 64 public static String inputStream2String(InputStream is) throws IOException { 65 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 66 int i = -1; 67 while ((i = is.read()) != -1) { 68 baos.write(i); 69 } 70 return baos.toString(); 71 } 72 73 // 流轉(zhuǎn)化成文件 74 public static void inputStream2File(InputStream is, String savePath) throws Exception { 75 System.out.println("文件保存路徑為:" + savePath); 76 File file = new File(savePath); 77 InputStream inputSteam = is; 78 BufferedInputStream fis = new BufferedInputStream(inputSteam); 79 FileOutputStream fos = new FileOutputStream(file); 80 int f; 81 while ((f = fis.read()) != -1) { 82 fos.write(f); 83 } 84 fos.flush(); 85 fos.close(); 86 fis.close(); 87 inputSteam.close(); 88 89 } 90 public static byte[] ReadPhoto(String path) { 91 File file = new File(path); 92 FileInputStream fin; 93 // 建一個緩沖保存數(shù)據(jù) 94 ByteBuffer nbf = ByteBuffer.allocate((int) file.length()); 95 byte[] array = new byte[1024]; 96 int offset = 0, length = 0; 97 byte[] content = null; 98 try { 99 fin = new FileInputStream(file); 100 while((length = fin.read(array)) > 0){ 101 if(length != 1024) nbf.put(array,0,length); 102 else nbf.put(array); 103 offset += length; 104 } 105 fin.close(); 106 content = nbf.array(); 107 } catch (FileNotFoundException e) { 108 // TODO Auto-generated catch block 109 e.printStackTrace(); 110 } catch (IOException e) { 111 // TODO Auto-generated catch block 112 e.printStackTrace(); 113 } 114 return content; 115 }
       1
      查詢數(shù)據(jù)庫update
      public class TestMethod { 2 public int insertImages(String desc,byte[] content) { 3 Connection con = DBcon.getConnection(); 4 PreparedStatement pstmt = null; 5 String sql = "update user set image = ? " + 6 "where userName = ? "; 7 int affCount = 0; 8 try { 9 pstmt = con.prepareStatement(sql); 10 pstmt.setBytes(1, content); 11 pstmt.setString(2, desc); 12 affCount = pstmt.executeUpdate(); 13 } catch (SQLException e1) { 14 // TODO Auto-generated catch block 15 e1.printStackTrace(); 16 } 17 return affCount; 18 } 19 }

       

      posted @ 2016-11-17 22:31  頭一回  閱讀(26424)  評論(1)    收藏  舉報
      主站蜘蛛池模板: 最新的国产成人精品2020| 精品亚洲精品日韩精品| 国产精品污一区二区三区| 亚洲日韩欧美丝袜另类自拍 | 亚洲国产婷婷综合在线精品| 福利在线视频一区二区| 乌审旗| 成人区人妻精品一区二区| 影音先锋男人站| 国产精品无码专区| 亚洲一区二区三区在线观看精品中文| 国产精品成人午夜久久| 一区二区三区综合在线视频| 亚洲成人av综合一区| 忘忧草在线社区www中国中文 | 国产精品视频亚洲二区| 久久精品国产亚洲av麻豆软件| 精品人妻少妇一区二区三区 | 人妻精品动漫h无码| 国产亚洲精品第一综合另类灬| 在线国产精品中文字幕| 国产喷水1区2区3区咪咪爱AV| 亚洲乱妇老熟女爽到高潮的片| 美女无遮挡免费视频网站| 日照市| 亚洲国产精品成人av网| 亚洲AV永久纯肉无码精品动漫| 无码人妻斩一区二区三区| av午夜福利一片看久久| 欧美牲交a欧美牲交aⅴ一| 黑人玩弄人妻中文在线| 浓毛老太交欧美老妇热爱乱| 久久夜色撩人国产综合av| av在线播放国产一区| 国产成人啪精品午夜网站| 精品国产熟女一区二区三区| 亚洲欧美不卡高清在线| 91网站在线看| 国产精品高清一区二区三区不卡 | 日韩精品亚洲专在线电影| 国产亚洲精品久久久久久无亚洲|