android 上传通过存储打开的文件 api 在 kitkat 中呈现
android upload file opened via by storage api presented in kitkat
使用下面的代码打开文件
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, READ_REQUEST_CODE);
使用下面的代码读取文件
ParcelFileDescriptor parcelFileDescriptor =AttachImageOnPost.this.getContentResolver()
.openFileDescriptor(data.getData(), "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Rect rect=new Rect(100, 100, 100, 100);
image.setImageBitmap(BitmapFactory.decodeFileDescriptor(fileDescriptor, rect));
有什么方法可以使用 HttpClient
上传文件
import java.io.File;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
public class SendImageHttpPost {
public static void sendPost(String url, String imagePath) throws IOException, ClientProtocolException {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost(url);
File file = new File(imagePath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
Log.e("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
Log.e(""+response.getStatusLine());
if (resEntity != null) {
Log.e(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
}
不过,我强烈建议您使用一些优秀的开源库,让您的任务更轻松、更整洁,例如 Ion:
Ion.with(getContext())
.load("https://koush.clockworkmod.com/test/echo")
.uploadProgressBar(uploadProgressBar)
.setMultipartParameter("goop", "noop")
.setMultipartFile("archive", "application/zip", new File("/sdcard/filename.zip"))
.asJsonObject()
.setCallback(...)
或截击:
UP loading file using input stream 解决了下面的问题是我的异步任务
public class GlobalMultiPart extends AsyncTask<Void, Void, Void> {
private static final String TAG = GlobalMultiPart.class.getSimpleName() ;
Uri uri;
HashMap<String, String> params;
String Url;
InputStream inputStream;
String displayName, imageKey;
boolean isInputStream = false;
public interface OnResponse {
void onResponse(String result);
void onError(String error);
}
OnResponse onResponse;
public GlobalMultiPart(Uri uri, HashMap<String, String> params, String url, OnResponse onResponse, String imageKey) {
if (params == null) {
params = new HashMap<>();
}
this.uri = uri;
this.params = params;
this.Url = url;
this.onResponse = onResponse;
this.imageKey = imageKey;
try {
readMetaData(uri);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected Void doInBackground(Void... params) {
uploadImage();
return null;
}
public void uploadImage() {
String Response = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(Url);
post.setEntity(hashMapToMultipart());
HttpResponse response1 = httpClient.execute(post);
HttpEntity resEntity = response1.getEntity();
Response = EntityUtils.toString(resEntity);
Log.i(SetupProfileActivity.class.getSimpleName(), Response);
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
e.printStackTrace();
}
if (Response == null)
onResponse.onError("An error occurred");
else
onResponse.onResponse(Response);
}
public MultipartEntity hashMapToMultipart() {
MultipartEntity mpEntity = new MultipartEntity();
if (uri != null) {
ContentBody cbFile1 = new InputStreamBody(inputStream, displayName);
mpEntity.addPart(imageKey, cbFile1);
}
try {
for (String key : params.keySet()) {
mpEntity.addPart(key, new StringBody(params.get(key)));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return mpEntity;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void readMetaData(Uri uri) {
try {
inputStream = AppController.getInstance().getApplicationContext().getContentResolver().openInputStream(uri);
isInputStream = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
displayName = uri.getLastPathSegment();
Cursor cursor = AppController.getInstance().getApplicationContext().getContentResolver().query(uri, null, null, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst())
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
cursor.close();
}
} finally {
L.d(TAG, "Cursor on multipart null");
}
}
}
使用下面的代码打开文件
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, READ_REQUEST_CODE);
使用下面的代码读取文件
ParcelFileDescriptor parcelFileDescriptor =AttachImageOnPost.this.getContentResolver()
.openFileDescriptor(data.getData(), "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Rect rect=new Rect(100, 100, 100, 100);
image.setImageBitmap(BitmapFactory.decodeFileDescriptor(fileDescriptor, rect));
有什么方法可以使用 HttpClient
import java.io.File;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
public class SendImageHttpPost {
public static void sendPost(String url, String imagePath) throws IOException, ClientProtocolException {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost(url);
File file = new File(imagePath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
Log.e("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
Log.e(""+response.getStatusLine());
if (resEntity != null) {
Log.e(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
}
不过,我强烈建议您使用一些优秀的开源库,让您的任务更轻松、更整洁,例如 Ion:
Ion.with(getContext())
.load("https://koush.clockworkmod.com/test/echo")
.uploadProgressBar(uploadProgressBar)
.setMultipartParameter("goop", "noop")
.setMultipartFile("archive", "application/zip", new File("/sdcard/filename.zip"))
.asJsonObject()
.setCallback(...)
或截击:
UP loading file using input stream 解决了下面的问题是我的异步任务
public class GlobalMultiPart extends AsyncTask<Void, Void, Void> {
private static final String TAG = GlobalMultiPart.class.getSimpleName() ;
Uri uri;
HashMap<String, String> params;
String Url;
InputStream inputStream;
String displayName, imageKey;
boolean isInputStream = false;
public interface OnResponse {
void onResponse(String result);
void onError(String error);
}
OnResponse onResponse;
public GlobalMultiPart(Uri uri, HashMap<String, String> params, String url, OnResponse onResponse, String imageKey) {
if (params == null) {
params = new HashMap<>();
}
this.uri = uri;
this.params = params;
this.Url = url;
this.onResponse = onResponse;
this.imageKey = imageKey;
try {
readMetaData(uri);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected Void doInBackground(Void... params) {
uploadImage();
return null;
}
public void uploadImage() {
String Response = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(Url);
post.setEntity(hashMapToMultipart());
HttpResponse response1 = httpClient.execute(post);
HttpEntity resEntity = response1.getEntity();
Response = EntityUtils.toString(resEntity);
Log.i(SetupProfileActivity.class.getSimpleName(), Response);
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
e.printStackTrace();
}
if (Response == null)
onResponse.onError("An error occurred");
else
onResponse.onResponse(Response);
}
public MultipartEntity hashMapToMultipart() {
MultipartEntity mpEntity = new MultipartEntity();
if (uri != null) {
ContentBody cbFile1 = new InputStreamBody(inputStream, displayName);
mpEntity.addPart(imageKey, cbFile1);
}
try {
for (String key : params.keySet()) {
mpEntity.addPart(key, new StringBody(params.get(key)));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return mpEntity;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void readMetaData(Uri uri) {
try {
inputStream = AppController.getInstance().getApplicationContext().getContentResolver().openInputStream(uri);
isInputStream = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
displayName = uri.getLastPathSegment();
Cursor cursor = AppController.getInstance().getApplicationContext().getContentResolver().query(uri, null, null, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst())
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
cursor.close();
}
} finally {
L.d(TAG, "Cursor on multipart null");
}
}
}