Android上传文件通过奇巧提供的存储API打开



用于在代码下面打开文件

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:

https://github.com/koush/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(...)

或Volley:

https://github.com/mcxiaoke/android-volley

使用输入流加载文件解决了下面的问题是我的异步任务

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");
        }
    }

} 

相关内容

  • 没有找到相关文章

最新更新