android base64传文件,android中通过转换Base64实现图片视屏等文件上传

在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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值