0
点赞
收藏
分享

微信扫一扫

利用AsyncHttpClient实现图片的上传与下载

waaagh 2023-06-04 阅读 77


图片上传

 



    1.       /**
    2. * @param path
    3. *            要上传的文件路径
    4. * @param url
    5. *            服务端接收URL
    6. * @throws Exception
    7. */  
    8. public static void uploadFile(String path, String url) throws Exception {  
    9. File file = new File(path);  
    10. if (file.exists() && file.length() > 0) {  
    11. new AsyncHttpClient();  
    12. new RequestParams();  
    13. "uploadfile", file);  
    14. // 上传文件  
    15. new AsyncHttpResponseHandler() {  
    16. @Override  
    17. public void onSuccess(int statusCode, Header[] headers,  
    18. byte[] responseBody) {  
    19. // 上传成功后要做的工作  
    20. "上传成功", Toast.LENGTH_LONG).show();  
    21. 0);  
    22.         }  
    23.   
    24. @Override  
    25. public void onFailure(int statusCode, Header[] headers,  
    26. byte[] responseBody, Throwable error) {  
    27. // 上传失败后要做到工作  
    28. "上传失败", Toast.LENGTH_LONG).show();  
    29.         }  
    30.   
    31. @Override  
    32. public void onProgress(int bytesWritten, int totalSize) {  
    33. // TODO Auto-generated method stub  
    34. super.onProgress(bytesWritten, totalSize);  
    35. int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);  
    36. // 上传进度显示  
    37.             progress.setProgress(count);  
    38. "上传 Progress>>>>>", bytesWritten + " / " + totalSize);  
    39.         }  
    40.   
    41. @Override  
    42. public void onRetry(int retryNo) {  
    43. // TODO Auto-generated method stub  
    44. super.onRetry(retryNo);  
    45. // 返回重试次数  
    46.         }  
    47.   
    48.     });  
    49. } else {  
    50. "文件不存在", Toast.LENGTH_LONG).show();  
    51. }



    图片下载


      1.       /**
      2. * @param url
      3. *            要下载的文件URL
      4. * @throws Exception
      5. */  
      6. public static void downloadFile(String url) throws Exception {  
      7.   
      8. AsyncHttpClient client = new AsyncHttpClient();  
      9. // 指定文件类型  
      10. String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" };  
      11. // 获取二进制数据如图片和其他文件  
      12. client.get(url, new BinaryHttpResponseHandler(allowedContentTypes) {  
      13.   
      14. @Override  
      15. public void onSuccess(int statusCode, Header[] headers,  
      16. byte[] binaryData) {  
      17.         String tempPath = Environment.getExternalStorageDirectory()  
      18. "/temp.jpg";  
      19. // TODO Auto-generated method stub  
      20. // 下载成功后需要做的工作  
      21. 0);  
      22. //  
      23. "binaryData:", "共下载了:" + binaryData.length);  
      24. //  
      25. 0,  
      26.                 binaryData.length);  
      27.   
      28. new File(tempPath);  
      29. // 压缩格式  
      30.         CompressFormat format = Bitmap.CompressFormat.JPEG;  
      31. // 压缩比例  
      32. int quality = 100;  
      33. try {  
      34. // 若存在则删除  
      35. if (file.exists())  
      36.                 file.delete();  
      37. // 创建文件  
      38.             file.createNewFile();  
      39. //  
      40. new FileOutputStream(file);  
      41. // 压缩输出  
      42.             bmp.compress(format, quality, stream);  
      43. // 关闭  
      44.             stream.close();  
      45. //  
      46. "下载成功\n" + tempPath,  
      47.                     Toast.LENGTH_LONG).show();  
      48.   
      49. catch (IOException e) {  
      50. // TODO Auto-generated catch block  
      51.             e.printStackTrace();  
      52.         }  
      53.   
      54.     }  
      55.   
      56. @Override  
      57. public void onFailure(int statusCode, Header[] headers,  
      58. byte[] binaryData, Throwable error) {  
      59. // TODO Auto-generated method stub  
      60. "下载失败", Toast.LENGTH_LONG).show();  
      61.     }  
      62.   
      63. @Override  
      64. public void onProgress(int bytesWritten, int totalSize) {  
      65. // TODO Auto-generated method stub  
      66. super.onProgress(bytesWritten, totalSize);  
      67. int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);  
      68. // 下载进度显示  
      69.         progress.setProgress(count);  
      70. "下载 Progress>>>>>", bytesWritten + " / " + totalSize);  
      71.   
      72.     }  
      73.   
      74. @Override  
      75. public void onRetry(int retryNo) {  
      76. // TODO Auto-generated method stub  
      77. super.onRetry(retryNo);  
      78. // 返回重试次数  
      79.     }  
      80.   
      81. });



      PHP服务端

       

       


      1. <?php  
      2. $base_path = "./upload/"; // 接收文件目录  
      3. $target_path = $base_path . basename ( $_FILES ['uploadfile'] ['name'] );  
      4. if (move_uploaded_file ( $_FILES ['uploadfile'] ['tmp_name'], $target_path )) {  
      5. $array = array (  
      6. "code" => "1",  
      7. "message" => $_FILES ['uploadfile'] ['name']   
      8.     );  
      9. echo json_encode ( $array );  
      10. } else {  
      11. $array = array (  
      12. "code" => "0",  
      13. "message" => "There was an error uploading the file, please try again!" . $_FILES ['uploadfile'] ['error']   
      14.     );  
      15. echo json_encode ( $array );  
      16. }  
      17. ?>


       

       

       

      Service中类似的异常问题:

      (com.zajt.zajtsafechat.http.AsyncHttpResponseHandler$ResponderHandler) {42843450} sending message to a Handler on a dead thread

      解决办法:

       在Service中,AsyncHttpClient client = new SyncHttpClient();

       在Activity中,AsyncHttpClient client = new AsyncHttpClient();

       

      其中SyncHttpClient是AsyncHttpClient的子类

      举报

      相关推荐

      0 条评论