利用AsyncHttpClient实现图片的上传与下载+进度条
2015-04-28 14:47
288 查看
利用AsyncHttpClient实现图片的上传与下载+
进度条
图片上传
[java] view
plaincopy
/**
* @param path
* 要上传的文件路径
* @param url
* 服务端接收URL
* @throws Exception
*/
public static void uploadFile(String path, String url) throws Exception {
File file = new File(path);
if (file.exists() && file.length() > 0) {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("uploadfile", file);
// 上传文件
client.post(url, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
// 上传成功后要做的工作
Toast.makeText(mContext, "上传成功", Toast.LENGTH_LONG).show();
progress.setProgress(0);
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
// 上传失败后要做到工作
Toast.makeText(mContext, "上传失败", Toast.LENGTH_LONG).show();
}
@Override
public void onProgress(int bytesWritten, int totalSize) {
// TODO Auto-generated method stub
super.onProgress(bytesWritten, totalSize);
int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
// 上传进度显示
progress.setProgress(count);
Log.e("上传 Progress>>>>>", bytesWritten + " / " + totalSize);
}
@Override
public void onRetry(int retryNo) {
// TODO Auto-generated method stub
super.onRetry(retryNo);
// 返回重试次数
}
});
} else {
Toast.makeText(mContext, "文件不存在", Toast.LENGTH_LONG).show();
}
图片下载
[java] view
plaincopy
/**
* @param url
* 要下载的文件URL
* @throws Exception
*/
public static void downloadFile(String url) throws Exception {
AsyncHttpClient client = new AsyncHttpClient();
// 指定文件类型
String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" };
// 获取二进制数据如图片和其他文件
client.get(url, new BinaryHttpResponseHandler(allowedContentTypes) {
@Override
public void onSuccess(int statusCode, Header[] headers,
byte[] binaryData) {
String tempPath = Environment.getExternalStorageDirectory()
.getPath() + "/temp.jpg";
// TODO Auto-generated method stub
// 下载成功后需要做的工作
progress.setProgress(0);
//
Log.e("binaryData:", "共下载了:" + binaryData.length);
//
Bitmap bmp = BitmapFactory.decodeByteArray(binaryData, 0,
binaryData.length);
File file = new File(tempPath);
// 压缩格式
CompressFormat format = Bitmap.CompressFormat.JPEG;
// 压缩比例
int quality = 100;
try {
// 若存在则删除
if (file.exists())
file.delete();
// 创建文件
file.createNewFile();
//
OutputStream stream = new FileOutputStream(file);
// 压缩输出
bmp.compress(format, quality, stream);
// 关闭
stream.close();
//
Toast.makeText(mContext, "下载成功\n" + tempPath,
Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] binaryData, Throwable error) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "下载失败", Toast.LENGTH_LONG).show();
}
@Override
public void onProgress(int bytesWritten, int totalSize) {
// TODO Auto-generated method stub
super.onProgress(bytesWritten, totalSize);
int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
// 下载进度显示
progress.setProgress(count);
Log.e("下载 Progress>>>>>", bytesWritten + " / " + totalSize);
}
@Override
public void onRetry(int retryNo) {
// TODO Auto-generated method stub
super.onRetry(retryNo);
// 返回重试次数
}
});
PHP服务端
[php] view
plaincopy
<?php
$base_path = "./upload/"; // 接收文件目录
$target_path = $base_path . basename ( $_FILES ['uploadfile'] ['name'] );
if (move_uploaded_file ( $_FILES ['uploadfile'] ['tmp_name'], $target_path )) {
$array = array (
"code" => "1",
"message" => $_FILES ['uploadfile'] ['name']
);
echo json_encode ( $array );
} else {
$array = array (
"code" => "0",
"message" => "There was an error uploading the file, please try again!" . $_FILES ['uploadfile'] ['error']
);
echo json_encode ( $array );
}
?>
Service中类似的异常问题:
(com.zajt.zajtsafechat.http.AsyncHttpResponseHandler$ResponderHandler) {42843450} sending message to a Handler on a dead thread
解决办法:
在Service中,AsyncHttpClient client = new SyncHttpClient();
在Activity中,AsyncHttpClient client = new AsyncHttpClient();
其中SyncHttpClient是AsyncHttpClient的子类
进度条
图片上传
[java] view
plaincopy
/**
* @param path
* 要上传的文件路径
* @param url
* 服务端接收URL
* @throws Exception
*/
public static void uploadFile(String path, String url) throws Exception {
File file = new File(path);
if (file.exists() && file.length() > 0) {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("uploadfile", file);
// 上传文件
client.post(url, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
// 上传成功后要做的工作
Toast.makeText(mContext, "上传成功", Toast.LENGTH_LONG).show();
progress.setProgress(0);
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
// 上传失败后要做到工作
Toast.makeText(mContext, "上传失败", Toast.LENGTH_LONG).show();
}
@Override
public void onProgress(int bytesWritten, int totalSize) {
// TODO Auto-generated method stub
super.onProgress(bytesWritten, totalSize);
int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
// 上传进度显示
progress.setProgress(count);
Log.e("上传 Progress>>>>>", bytesWritten + " / " + totalSize);
}
@Override
public void onRetry(int retryNo) {
// TODO Auto-generated method stub
super.onRetry(retryNo);
// 返回重试次数
}
});
} else {
Toast.makeText(mContext, "文件不存在", Toast.LENGTH_LONG).show();
}
图片下载
[java] view
plaincopy
/**
* @param url
* 要下载的文件URL
* @throws Exception
*/
public static void downloadFile(String url) throws Exception {
AsyncHttpClient client = new AsyncHttpClient();
// 指定文件类型
String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" };
// 获取二进制数据如图片和其他文件
client.get(url, new BinaryHttpResponseHandler(allowedContentTypes) {
@Override
public void onSuccess(int statusCode, Header[] headers,
byte[] binaryData) {
String tempPath = Environment.getExternalStorageDirectory()
.getPath() + "/temp.jpg";
// TODO Auto-generated method stub
// 下载成功后需要做的工作
progress.setProgress(0);
//
Log.e("binaryData:", "共下载了:" + binaryData.length);
//
Bitmap bmp = BitmapFactory.decodeByteArray(binaryData, 0,
binaryData.length);
File file = new File(tempPath);
// 压缩格式
CompressFormat format = Bitmap.CompressFormat.JPEG;
// 压缩比例
int quality = 100;
try {
// 若存在则删除
if (file.exists())
file.delete();
// 创建文件
file.createNewFile();
//
OutputStream stream = new FileOutputStream(file);
// 压缩输出
bmp.compress(format, quality, stream);
// 关闭
stream.close();
//
Toast.makeText(mContext, "下载成功\n" + tempPath,
Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] binaryData, Throwable error) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "下载失败", Toast.LENGTH_LONG).show();
}
@Override
public void onProgress(int bytesWritten, int totalSize) {
// TODO Auto-generated method stub
super.onProgress(bytesWritten, totalSize);
int count = (int) ((bytesWritten * 1.0 / totalSize) * 100);
// 下载进度显示
progress.setProgress(count);
Log.e("下载 Progress>>>>>", bytesWritten + " / " + totalSize);
}
@Override
public void onRetry(int retryNo) {
// TODO Auto-generated method stub
super.onRetry(retryNo);
// 返回重试次数
}
});
PHP服务端
[php] view
plaincopy
<?php
$base_path = "./upload/"; // 接收文件目录
$target_path = $base_path . basename ( $_FILES ['uploadfile'] ['name'] );
if (move_uploaded_file ( $_FILES ['uploadfile'] ['tmp_name'], $target_path )) {
$array = array (
"code" => "1",
"message" => $_FILES ['uploadfile'] ['name']
);
echo json_encode ( $array );
} else {
$array = array (
"code" => "0",
"message" => "There was an error uploading the file, please try again!" . $_FILES ['uploadfile'] ['error']
);
echo json_encode ( $array );
}
?>
Service中类似的异常问题:
(com.zajt.zajtsafechat.http.AsyncHttpResponseHandler$ResponderHandler) {42843450} sending message to a Handler on a dead thread
解决办法:
在Service中,AsyncHttpClient client = new SyncHttpClient();
在Activity中,AsyncHttpClient client = new AsyncHttpClient();
其中SyncHttpClient是AsyncHttpClient的子类
相关文章推荐
- 利用AsyncHttpClient实现图片的上传与下载
- 利用AsyncHttpClient实现图片的上传与下载
- 简单实现的自定义圆环进度条,可使用于文件的上传下载图片加载等地方.
- Objective-C利用AFN实现图片下载,支持断点续传,显示下载进度
- AsyncHttpClient实现上传 HttpURLConnection实现下载
- Java利用apache ftp工具实现文件上传下载和删除功能
- 微信公共服务平台开发(.Net 的实现)8-------处理图片(上传下载发送)
- js实现图片上传预览及进度条
- 折腾:利用Node.js+express框实现图片上传
- php程序中实现图片的上传和下载
- 利用WebService实现远程服务器文件的上传和下载
- 【WCF】利用WCF实现上传下载文件服务
- Android利用FTP实现与PC的上传和下载,实现二维码扫描下载
- 使用httpclient实现上传下载(javaWeb系统数据传输http实现)
- 利用jQuery插件imgAreaSelect实现图片上传裁剪(同步显示图像位置信息)
- 利用WCF实现上传下载文件服务
- PHP持续保有长连接,利用flush()持续更新浏览器UI,下载进度条实现
- 网络数据请求实践一:android-async-http实现下载和上传
- 利用js实现无刷新上传头像(或文件)并显示进度条
- 一行代码实现Okhttp,Retrofit,Glide下载上传进度监听