当然,这里需要首先导入asyncHttpClient依赖的jar包
上传文件的基本操作步骤:
明确读取文件的路径与上传文件的地址 依据文件的路径将上传文件封装为File 依据上传文件的目标地址设置网络请求的方式 进行文件的上传的操作 获取文件上传的结果
//上传文件的路径
private String uploadLocaleUrl=""
//上传文件的目的地址
private String uploadServletUrl=""
//点击按钮 进行文件上传
public void click(View v) {
//依据上传文件的路径 构建file 对象
File file = new File(uploadLocaleUrl);
if (file.exists()&&file.length()>0) {
//获取asynchttpclient的实例
AsyncHttpClient client = new AsyncHttpClient();
//进行文件的上传 发送一个post请求
RequestParams params = new RequestParams();
try {
params.put("profile_picture", file);// Upload a File
} catch (FileNotFoundException e) {
e.printStackTrace();
}
client.post(uploadUrl, params, new AsyncHttpResponseHandler() {
//上传成功后 调用这个方法
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Toast.makeText(getApplicationContext(), "上传成功", 0).show();
}
@Override
public void onProgress(int bytesWritten, int totalSize) {
//设置进度条的总大小
pb_bar.setMax(totalSize);
//设置进度条的当前进度
pb_bar.setProgress(bytesWritten);
super.onProgress(bytesWritten, totalSize);
}
//上传失败
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
}
});
}else {
System.out.println("请检测文件对象 ...");
}
注意:需要添加连网的权限
使用这种方法比较麻烦,封装的参数比较多
//上传文件的地址路径
private String uploadServiletUrl = "";
//上传文件的路径
private String uploadLocaleUrl = "";
private void uploadFile()
{
String end = "/r/n";
String Hyphens = "--";
String boundary = "*****";
File file = new File(uploadLocaleUrl);
try
{
URL url = new URL(uploadServiletUrl);
//创建一个连接
HttpURLConnection con = (HttpURLConnection) url.openConnection();
/* 允许Input、Output,不使用Cache */
con.setDoInput(true);//允许输入流
con.setDoOutput(true);//允许输出流
con.setUseCaches(false);//设置不使用缓存
//设定请求的方式为post
con.setRequestMethod("POST");
//设定请求的参数
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
//设定输出流
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
ds.writeBytes(Hyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; "+"name=/"+file+"/"+"newName/"+end);
ds.writeBytes(end);
/* 取得文件的FileInputStream */
FileInputStream fStream = new FileInputStream(uploadLocaleUrl);
/* 设定每次写入1024bytes */
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
/* 从文件读取数据到缓冲区 */
while ((length = fStream.read(buffer)) != -1)
{
/* 将数据写入DataOutputStream中 */
ds.write(buffer, 0, length);
}
ds.writeBytes(end);
ds.writeBytes(Hyphens + boundary + Hyphens + end);
fStream.close();
ds.flush();
//获取服务器返回的数据
InputStream is = con.getInputStream();
int ch;
StringBuffer stringBuffer= new StringBuffer();
while ((ch = is.read()) != -1)
{
stringBuffer.append((char) ch);
}
System.out.println("上传成功");;
ds.close();
} catch (Exception e)
{
System.out.println("上传失败" + e.getMessage());
}
}