gpt4 book ai didi

java - android上传文件通过kitkat中提供的存储api打开

转载 作者:行者123 更新时间:2023-12-01 11:13:40 24 4
gpt4 key购买 nike

使用下面的代码打开文件

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

关于java - android上传文件通过kitkat中提供的存储api打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32096152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com