使用意图上传图片
Posted
技术标签:
【中文标题】使用意图上传图片【英文标题】:Image Upload using intent 【发布时间】:2015-12-25 19:27:28 【问题描述】:我正在尝试为我的 android 移动应用程序上传图片。该代码适用于从图库文件夹上传的图像。但是,如果我从“最近的图像”、“文档”、“下载”中选择任何图像,则图像路径未提取并且无法上传图像。你能帮我解决这个问题吗?
这是我的代码供您参考:
package com.example.imageupload;
public class MainActivity extends Activity
private ImageView image;
private Button uploadButton;
private Bitmap bitmap;
private Button selectImageButton, takeImageButton;
String link = uri;
// number of images to select
private static final int PICK_IMAGE = 1;
private static final int CAMERA_REQUEST = 1888;
/**
* called when the activity is first created
*/
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find the views
image = (ImageView) findViewById(R.id.uploadImage);
uploadButton = (Button) findViewById(R.id.uploadButton);
takeImageButton = (Button) findViewById(R.id.takeImageButton);
selectImageButton = (Button) findViewById(R.id.selectImageButton);
selectImageButton.setOnClickListener(new OnClickListener()
@Override
public void onClick(View v)
selectImageFromGallery();
);
// when uploadButton is clicked
uploadButton.setOnClickListener(new OnClickListener()
@Override
public void onClick(View v)
// new ImageUploadTask().execute();
Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT)
.show();
uploadTask();
);
protected void uploadTask()
// TODO Auto-generated method stub
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
String file = Base64.encodeToString(data, 0);
Log.i("base64 string", "base64 string: " + file);
new ImageUploadTask(file).execute();
/**
* Opens dialog picker, so the user can select image from the gallery. The
* result is returned in the method <code>onActivityResult()</code>
*/
public void selectImageFromGallery()
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE);
/**
* Retrives the result returned from selecting image, by invoking the method
* <code>selectImageFromGallery()</code>
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK
&& null != data)
Uri selectedImage = data.getData();
String[] filePathColumn = MediaStore.Images.Media.DATA ;
/*
* Cursor cursor = getContentResolver().query(selectedImage,
* filePathColumn, null, null, null);
*/
Cursor cursor = managedQuery(selectedImage, filePathColumn, null,
null, null);
cursor.moveToFirst();
// int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
int columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String picturePath = cursor.getString(columnIndex);
Log.i("picturePath", "picturePath: " + picturePath);
cursor.close();
decodeFile(picturePath);
public void decodeFile(String filePath)
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true)
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
image.setImageBitmap(bitmap);
/**
* The class connects with server and uploads the photo
*
*
*/
class ImageUploadTask extends AsyncTask<Void, Void, String>
String base64_string;
public ImageUploadTask(String file)
// TODO Auto-generated constructor stub
this.base64_string = file;
@Override
protected String doInBackground(Void... params)
// TODO Auto-generated method stub
ArrayList<NameValuePair> postData;
postData = new ArrayList<NameValuePair>();
JSONObject parentData = new JSONObject();
JSONObject childData = new JSONObject();
try
childData.put("fileContent", base64_string);
childData.put("fileName", "droid.jpeg");
childData.put("fileType", "I");
// System.out.println(childData);
parentData.put("mobile", childData);
System.out.println(parentData);
catch (JSONException e)
e.printStackTrace();
// postData.add(new BasicNameValuePair("User",
// childData.toString()));
InputStream is = null;
String jsonResponse = "";
JSONObject jObj = null;
try
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(
"URL");
request.setHeader("Content-Type", "application/json");
request.setEntity(new StringEntity(parentData.toString()));
HttpResponse httpResponse = httpClient.execute(request);
System.out.println(httpResponse);
// HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
System.out.println(httpEntity);
is = httpEntity.getContent();
System.out.println(is);
System.out.println(is.toString());
try
Log.e("@@@@@@@@@@", "@@@@@@@@@@@");
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
is.close();
jsonResponse = sb.toString();
Log.e("JSON", "Check Json: " + jsonResponse);
catch (Exception e)
Log.e("Buffer Error",
"Error converting result " + e.toString());
catch (UnsupportedEncodingException e)
e.printStackTrace();
catch (ClientProtocolException e)
e.printStackTrace();
catch (IOException e)
e.printStackTrace();
return null;
【问题讨论】:
你有什么解决办法吗?我面临同样的问题。 @HarshalBhatt,我对我的代码进行了以下更改,它运行良好。请尝试一下,prntscr.com/b53eut 是的,它成功了。谢谢! @HarshalBhatt,请您在下面向上回答我的答案。 【参考方案1】:我只是将代码更改如下:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && null != data)
if (resultCode == getActivity().RESULT_OK)
selectedImage = data.getData();
Log.i("selectedImage", "selectedImage: " + selectedImage.toString());
String[] filePathColumn = MediaStore.Images.Media.DATA;
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
Log.i("columnIndex", "columnIndex: " + columnIndex);
String picturePath = cursor.getString(columnIndex);
Log.i("picturePath", "picturePath: " + picturePath);
cursor.close();
public void selectImageFromGallery()
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_IMAGE);
【讨论】:
以上是关于使用意图上传图片的主要内容,如果未能解决你的问题,请参考以下文章
vue移动端图片上传,可最多上传9张,使用webuploader插件
原生方式实现图片,文件上传,和使用ElmentUI使用Drag方式自动上传图片,手动上传图片