1.在AndroidManifest.xml中添加以下权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2.在build.gradle中添加以下依赖:
implementation 'com.alibaba.cloud:aliyun-oss-android-sdk:3.0.4'
implementation 'com.alibaba.cloud:aliyun-oss-common-utils:3.0.4'
3.初始化OSSClient:
String accessKeyId = "your_accessKeyId";
String accessKeySecret = "your_access_key_secret";
String endpoint = "your_oss_endpoint";
String bucketName = "your_bucket_name";
// 创建OSSClient实例。
OSS oss = new OSSClient(getApplicationContext(), endpoint, new OSSCredentialProvider() {
@Override
public OSSCredential getCredentials() {
OSSCredential ossCredential = new OSSPlainTextAKSKCredential(accessKeyId, accessKeySecret);
return ossCredential;
}
});
4.选择文件:
private static final int REQUEST_CODE = 0x01;
// 选择文件
public void selectFile(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, REQUEST_CODE);
}
// 处理选择结果
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
Uri uri = data.getData();
String filePath = FileUtils.getPath(this, uri);
Log.d("TAG", "filePath = " + filePath);
// 开始上传文件
uploadFile(filePath);
}
}
5.上传文件:
// 上传文件
private void uploadFile(final String filePath) {
// 构造上传请求
PutObjectRequest put = new PutObjectRequest(bucketName, "test.jpg", filePath);
// 异步上传
OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
@Override
public void onSuccess(PutObjectRequest request, PutObjectResult result) {
Log.d("TAG", "文件上传成功");
// TODO: 处理文件上传成功的回调
}
@Override
public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
Log.e("TAG", "文件上传失败");
// TODO: 处理文件上传失败的回调
}
});
}
6.辅助类:
public class FileUtils {
/**
* 根据Uri返回文件绝对路径
* @param context 上下文
* @param uri 文件Uri
*/
public static String getPath(final Context context, final Uri uri) {
// DocumentProvider
if (DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* 获取文件Uri关联的数据列值
* @param context 上下文
* @param uri 文件Uri
* @param selection 查询条件
* @param selectionArgs 查询条件参数
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* 判断Uri是否为ExternalStorageProvider
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* 判断Uri是否为DownloadsProvider
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* 判断Uri是否为MediaProvider
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* 判断Uri是否为Google Photos Uri
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}
您好,我是AI助手。关于Android文件上传,可以使用 HttpURLConnection 或者 OkHttp 等安卓原生网络请求库。以下是一个简单的上传文件的代码示例:
private void uploadFile(String url, File file) {
try {
String boundary = "---------------------------" + System.currentTimeMillis();
URL uploadUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) uploadUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes("--" + boundary + "rn");
dos.writeBytes("Content-Disposition: form-data; name="file"; filename="" + file.getName() + ""rn");
dos.writeBytes("Content-Type: application/octet-streamrnrn");
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
dos.write(buffer, 0, len);
}
fis.close();
dos.writeBytes("rn--" + boundary + "--rn");
dos.flush();
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
is.close();
}
dos.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
上述代码中,uploadFile 方法接受两个参数:上传服务器的 URL 和要上传的文件。在方法中,我们使用 HttpURLConnection 建立了一个 POST 请求,设置请求参数,读取文件的内容并写入到请求体中,最后等待响应。
需要注意的是,文件上传通常会比较耗时,建议在新线程中进行上传操作,以避免阻塞主线程。另外,建议对上传的文件进行压缩处理,以减少文件大小,提高上传速度。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/116155.html