使用android studio中的async-http-client库将图像上传到服务器

时间:2016-01-12 09:16:57

标签: android android-asynctask

我的结果是状态代码为0,但无法上传 我不知道为什么?

你可以帮我解决一下吗? 提前谢谢

这是我的代码

pickImage()用于从图库中选取图像

public void pickImage(){
  Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  startActivityForResult(galleryIntent, IMAGE_FROM_GALLERY);
}

onActivityResult

public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if(requestCode == IMAGE_FROM_GALLERY && resultCode == RESULT_OK && data != null) {
      ImageService imageService = new ImageService(this);
      imageService.uploadImage(new File(data.getData().getPath()), this.user);
  }

uploadImage方法用于连接服务器

public void uploadImage(File file, User user) {
    String baseUrl = Config.getHostName() + Service.ActionURL.upload_avatar;

    Service imageService = new Service();
    imageService.setHeader(imageService);
    imageService.put("uid", user.getUid());
    imageService.put("file", file);
    imageService.post(baseUrl, imageService.setParams(imageService.postParams), new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            Log.d("IMAGE", "onSuccess : " + statusCode);
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            Log.d("IMAGE", "onFailure : " + statusCode);
        }
    });
}

记录cat就像这样记录

01-12 22:15:16.959    1678-1678/com.plus.app D/IMAGE﹕ onFailure statusCode : 0

我的API服务器文档与我的Android应用程序连接

{
    "uid"   : varchar(255), //Cannot be changed
    "file"  : File(Binary) 
}

1 个答案:

答案 0 :(得分:0)

public void uploadImage(Bitmap bitmap){

        RequestParams request = new RequestParams();
        if (bitmap != null) {
            byte[] imagebyte;
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bao);
            imagebyte = bao.toByteArray();
            request.put("profile_picture", new ByteArrayInputStream(
                    imagebyte), "profile" + System.currentTimeMillis()
                    + ".png");
        }

        AsyncHttpClient client = new AsyncHttpClient();

        client.post("url", request, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onFailure(int arg0, Header[] arg1, byte[] arg2,
                    Throwable arg3) {
                // TODO Auto-generated method stub

            }
        });
}