将图像上传到服务器 android [英] Uploading Images to Server android

查看:24
本文介绍了将图像上传到服务器 android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在不降低质量的情况下将图像上传到服务器的最佳方式是什么.我在谷歌上搜索过,找到了各种发布数据的方法.但我不确定上传哪一个最好.我遇到了

I wanted to know which is the best way to upload image to server without loosing its quality. I have searched on google found various methods of posting data. But I am not sure which one would be best to upload. I came across

  1. 分段图像上传.
  2. 使用字节数组上传图片
  3. 使用 base64 编码的字符串上传图像.

我尝试过 Base64 编码,如果图像分辨率太高,它会导致 OOM(内存不足).任何解决此问题的教程将不胜感激.提前致谢.

I have tried Base64 encoding it leads me to OOM(Out of memory) if image is too high in resolution. Any tutorial which tackle this issue would be appreciated. Thanks in advance.

推荐答案

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);

从图库中选择图像的以上代码

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1)
        if (resultCode == Activity.RESULT_OK) {
            Uri selectedImage = data.getData();

            String filePath = getPath(selectedImage);
            String file_extn = filePath.substring(filePath.lastIndexOf(".") + 1);
            image_name_tv.setText(filePath);

            try {
                if (file_extn.equals("img") || file_extn.equals("jpg") || file_extn.equals("jpeg") || file_extn.equals("gif") || file_extn.equals("png")) {
                    //FINE
                } else {
                    //NOT IN REQUIRED FORMAT
                }
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
}

public String getPath(Uri uri) {
    String[] projection = {MediaColumns.DATA};
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    column_index = cursor
            .getColumnIndexOrThrow(MediaColumns.DATA);
    cursor.moveToFirst();
    imagePath = cursor.getString(column_index);

    return cursor.getString(column_index);
}

现在使用多部分表单数据发布数据

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("LINK TO SERVER");

多部分表单数据

MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
if (filePath != null) {
    File file = new File(filePath);
    Log.d("EDIT USER PROFILE", "UPLOAD: file length = " + file.length());
    Log.d("EDIT USER PROFILE", "UPLOAD: file exist = " + file.exists());
    mpEntity.addPart("avatar", new FileBody(file, "application/octet"));
}

最终将数据发布到服务器

httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);

这篇关于将图像上传到服务器 android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆