android上传下载图片demo
时间: 2023-07-06 16:02:16 浏览: 152
Android高级应用源码-最近在做关于上传多张图片的项目,需要选择多张图片,所以就做了个demo,仅供大家参考.zip
### 回答1:
android上传下载图片的示例代码如下:
首先,要确保在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
以下是一个上传图片的示例代码:
```java
public void uploadImage(String imagePath) {
File file = new File(imagePath);
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image", file.getName(),
RequestBody.create(MediaType.parse("image/*"), file))
.build();
Request request = new Request.Builder()
.url("http://example.com/upload")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 上传失败
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// 上传成功
String responseBody = response.body().string();
// 根据返回的数据处理结果
}
});
}
```
以下是一个下载图片的示例代码:
```java
public void downloadImage(String imageUrl, String savePath) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(imageUrl)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 下载失败
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// 下载成功
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = response.body().byteStream();
outputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
});
}
```
这些示例代码演示了如何使用OkHttp库发送HTTP请求来进行图片的上传和下载。上传图片时,使用MultipartBody将图片加入请求体中;下载图片时,将网络数据流写入本地文件。在回调方法中,可以处理上传和下载的结果。
### 回答2:
Android上传下载图片的Demo可以通过使用HttpClient或者OkHttp库来实现。以下是一个简单的示例代码:
1. 首先,在AndroidManifest.xml文件中添加以下权限:
```
<uses-permission android:name="android.permission.INTERNET" />
```
2. 创建一个名为ImageUploadDownload的类,包含上传和下载图片的方法。
```java
public class ImageUploadDownload {
// 上传图片
public static void uploadImage(String imageUrl, String uploadUrl) throws IOException {
File file = new File(imageUrl);
MultipartBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image", file.getName(),
RequestBody.create(MediaType.parse("image/jpeg"), file))
.build();
Request request = new Request.Builder()
.url(uploadUrl)
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("上传失败:" + response);
}
}
// 下载图片
public static void downloadImage(String imageUrl, final String savePath) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(imageUrl)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("下载失败:" + response);
}
InputStream inputStream = response.body().byteStream();
File file = new File(savePath);
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
fileOutputStream.close();
inputStream.close();
}
});
}
}
```
3. 在需要上传或者下载图片的地方,调用上述方法:
```java
String imageUrl = "/sdcard/pic.png";
String uploadUrl = "http://example.com/upload";
String savePath = "/sdcard/downloaded.png";
try {
ImageUploadDownload.uploadImage(imageUrl, uploadUrl);
ImageUploadDownload.downloadImage(imageUrl, savePath);
} catch (IOException e) {
e.printStackTrace();
}
```
需要注意的是,这只是一个简单的示例代码,实际使用时还需要添加错误处理和参数验证等功能。
### 回答3:
Android上传下载图片的demo可以分为两部分来实现,一部分是上传图片,另一部分是下载图片。以下是一个简单的示例代码:
上传图片的demo代码:
1. 首先,在AndroidManifest.xml文件中加入网络权限:
<uses-permission android:name="android.permission.INTERNET" />
2. 在布局文件中添加一个ImageView和一个Button用于选择图片:
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/selectButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选择图片" />
3. 在Activity中获取ImageView和Button的引用,并添加点击事件:
ImageView imageView = findViewById(R.id.imageView);
Button selectButton = findViewById(R.id.selectButton);
selectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_CODE);
}
});
4. 在onActivityResult方法中获取选择的图片的Uri,并将其转化为Bitmap,然后通过网络请求将图片上传:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
// 将bitmap转换为二进制数据
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
// 发送网络请求进行图片上传
// ...
}
}
下载图片的demo代码:
1. 首先,在布局文件中添加一个ImageView和一个Button用于下载图片:
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/downloadButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下载图片" />
2. 在Activity中获取ImageView和Button的引用,并添加点击事件:
ImageView imageView = findViewById(R.id.imageView);
Button downloadButton = findViewById(R.id.downloadButton);
downloadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DownloadImageTask(imageView).execute(IMAGE_URL);
}
});
3. 编写一个异步任务DownloadImageTask用于下载图片,并将下载的图片设置到ImageView中:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
private ImageView imageView;
public DownloadImageTask(ImageView imageView) {
this.imageView = imageView;
}
@Override
protected Bitmap doInBackground(String... urls) {
String imageUrl = urls[0];
Bitmap bitmap = null;
try {
InputStream in = new URL(imageUrl).openStream();
bitmap = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e(TAG, "Error: " + e.getMessage());
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
imageView.setImageBitmap(result);
}
}
}
以上是一个简单的Android上传下载图片的demo,上传图片时需要进行网络请求将图片转换为二进制数据并发送,下载图片时使用异步任务进行网络请求并将下载的图片设置到ImageView中。
阅读全文