Android上傳圖片到伺服器

來源:互聯網
上載者:User

標籤:

一.android需要匯入非同步請求的jar包 AsyncHttpClient 

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();//將圖片的位元組流資料加密成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();        }    }

二.伺服器的代碼(用的是springmvc)

@RequestMapping("/post")    public void post(HttpServletResponse response , Post post            //,MultipartFile image            ,String image            )throws IOException{        Receipt receipt = new Receipt();        try {            /*// 二進位流  上傳圖片            if(image!=null && image.getOriginalFilename()!=null && image.getOriginalFilename().length()>0){                //原始名稱                String originalFilename = image.getOriginalFilename();                //新的圖片名稱                String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));                String saveName = ImageUtil.findFilePathByFileName(newFileName);                System.out.println("O______________________________________K");                //新圖片                File newFile = new File(saveName);                if(!newFile.exists()){                    newFile.mkdir();                }                //將記憶體中的資料寫入磁碟                image.transferTo(newFile);                System.out.println("O______________________________________");                //將新圖片名稱寫到itemsCustom中                post.setImg(newFileName);            }else {                post.setImg("");            }*/            //  =================================                 字串接收檔案            if(image!=null && image.length()>0){                               byte[] photoimg = new BASE64Decoder().decodeBuffer(image);                  for (int i = 0; i < photoimg.length; ++i) {                      if (photoimg[i] < 0) {                          // 調整異常資料                          photoimg[i] += 256;                      }                  }                 String newFileName = UUID.randomUUID() + ".png";                String saveName = ImageUtil.findFilePathByFileName(newFileName);                File newFile = new File(saveName);                if(!newFile.exists()){                    newFile.createNewFile();                }                FileOutputStream out = new FileOutputStream(newFile);                  out.write(photoimg);                  out.flush();                  out.close();                  post.setImg(newFileName);                logger.debug("檔案接收成功");            }else {                post.setImg("");            }

三.工具類

public static String rootPathString = "WebRoot/WEB-INF/upload";        public static String findFilePathByFileName(String fileName) {        if(fileName == null || fileName.trim().isEmpty()){            return "/default.png";        }        int hashcode = fileName.hashCode();        int dir1 = hashcode&0xf;  //0--15        int dir2 = (hashcode&0xf0)>>4;  //0-15        String dir = rootPathString + "/" + dir1 + "/" + dir2;  //upload\2\3  upload\3\5        File file = new File(dir);        if(!file.exists()){            //建立目錄            file.mkdirs();        }        return dir+"/"+fileName;    }

 




 

ncHttpClient  

Android上傳圖片到伺服器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.