在android开发中我们经常会实现例如一些图片等流文件的上传。接下来介绍一种转换为Base64 然后通过post的参数形式上传.
/**
* 图片文件转Base64字符串
* @param path 文件所在的绝对路径加文件名
* @return
*/
private String fileBase64String(String path){
try {
FileInputStream fis = new FileInputStream(path);//转换成输入流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count = 0;
while((count = fis.read(buffer)) >= 0){
baos.write(buffer, 0, count);//读取输入流并写入输出字节流中
}
fis.close();//关闭文件输入流
String uploadBuffer = new String(Base64.encodeToString(baos.toByteArray(),Base64.DEFAULT)); //进行Base64编码
return uploadBuffer;
} catch (Exception e) {
return null;
}
}
我们首先可以通过此方法把文件转换成String 然后通过Post请求中的Params 传入。
map.put("image",fileBase64String(filePath+fileName));
private String requestPost(String urlPath, String params, OnJsonResponse onJsonResponse){
String bodyStr = fileBase64String(filePath+fileName);
byte[] data = bodyStr.getBytes();//获得请求体
try {
URL url = new URL(urlPath);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setConnectTimeout(timeoutMillis); //设置连接超时时间
httpURLConnection.setDoInput(true); //打开输入流,以便从服务器获取数据
httpURLConnection.setDoOutput(true); //打开输出流,以便向服务器提交数据
httpURLConnection.setRequestMethod("POST"); //设置以Post方式提交数据
httpURLConnection.setUseCaches(false); //使用Post方式不能使用缓存
//设置请求体的类型是文本类型
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//设置请求体的长度
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
//获得输出流,向服务器写入数据
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(data);
int response = httpURLConnection.getResponseCode(); //获得服务器的响应码
if(response == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpURLConnection.getInputStream();
String result = dealResponseResult(inputStream);
if(onJsonResponse != null){
onJsonResponse.onJsonReceived(urlPath, request_success, result);
}
Log.w(TAG,"result = " + result);
return result; //处理服务器的响应结果
}else{
if(onJsonResponse != null){
onJsonResponse.onJsonReceived(urlPath, request_failure, "fail code : " + response);
}
}
} catch (IOException e) {
e.printStackTrace();
if(onJsonResponse != null){
onJsonResponse.onJsonReceived(urlPath, request_failure, "fail msg : " + e.getMessage());
}
}
return null;
}
热门评论
附上demo学习就更完美了,不错
这么好的文章怎么可以没有评论