Android上传头像并下载头像缓存到本地
时间: 2023-09-27 07:05:35 浏览: 239
在Android中,可以通过使用Retrofit等网络请求库来实现头像的上传和下载,并将头像缓存到本地。以下是一个简单的示例:
1. 添加Retrofit和OkHttp依赖:
```gradle
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
```
2. 定义上传和下载接口:
```java
public interface ApiService {
@Multipart
@POST("upload_avatar")
Call<ResponseBody> uploadAvatar(@Part MultipartBody.Part file);
@GET("download_avatar")
Call<ResponseBody> downloadAvatar();
}
```
在上述代码中,使用@Multipart注解标记上传的请求,@Part注解标记上传的文件。下载接口使用@GET注解标记,并返回一个ResponseBody对象。
3. 实现上传头像的逻辑:
```java
// 选择图片并上传头像
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 1);
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri uri = data.getData();
File file = new File(getRealPathFromUri(this, uri));
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
ApiService apiService = createApiService();
Call<ResponseBody> call = apiService.uploadAvatar(filePart);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Toast.makeText(MainActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
}
});
}
}
// 获取URI对应的真实路径
public String getRealPathFromUri(Context context, Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
String filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
return "";
}
```
在上述代码中,使用Intent.ACTION_GET_CONTENT打开文件选择器,选择图片后将图片文件构造成RequestBody和MultipartBody.Part对象,然后使用Retrofit上传头像。
4. 实现下载头像并缓存到本地的逻辑:
```java
// 下载头像并缓存到本地
ApiService apiService = createApiService();
Call<ResponseBody> call = apiService.downloadAvatar();
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try (InputStream inputStream = response.body().byteStream()) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
// 将头像保存到本地文件
File file = new File(getCacheDir(), "avatar.png");
try (FileOutputStream fos = new FileOutputStream(file)) {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
}
});
```
在上述代码中,使用Retrofit下载头像,如果下载成功,将头像设置到ImageView中,并将头像保存到本地文件中。需要注意的是,下载头像时需要在异步线程中执行,否则会抛出NetworkOnMainThreadException异常。
阅读全文