文件与base64与字符串之间的转换

来源:互联网 发布:医学论文翻译软件 编辑:程序博客网 时间:2024/06/07 13:19
本人是去年刚毕业的学生,第一次写技术类的博客,还请各位多多指教。

今天说的是文件与base64之间的转换,在做项目的时候会遇到一些本地的文件上传到服务器上。我们可以用base64将文件转换成字符串,在通过POST请求上传到服务器(顺便说一下为什么用POST 请求。刚进公司,POST请求和GET请求一直搞不明白,被组长各种教育,其实简单的说就是GET请求是有受长度限制的,而POST请求不受长度限制,GET数据会附在URL之后如Login.asp?username=,而POST把数据放在HTTP包的包体中,另外POST服务端接受数据要用一个类来接收)

言归正传,这个原理搞懂之后,我们就可以上传 图片、视频、语音到服务器上,这些原理都是一样的,文件转换成字符串的代码:

public static String fileToBase64(File file) {String base64 = null;InputStream in = null;try {in = new FileInputStream(file);byte[] bytes = new byte[in.available()];int length = in.read(bytes);base64 = Base64.encodeToString(bytes, 0, length, Base64.DEFAULT);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {try {in.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return base64;}

我们可以把base64编码返回的字符串POST到服务端上,进行文件的保存,或者存入数据库.

我们也可以把字符串通过base64解码写入到文件里代码:

public static File base64ToFile(String base64) {File file = null;String fileName = "myvoice/testFile.arm";FileOutputStream out = null;try {// 解码,然后将字节转换为文件file = new File(Environment.getExternalStorageDirectory(), fileName);if (!file.exists())file.createNewFile();byte[] bytes = Base64.decode(base64, Base64.DEFAULT);// 将字符串转换为byte数组ByteArrayInputStream in = new ByteArrayInputStream(bytes);byte[] buffer = new byte[1024];out = new FileOutputStream(file);int bytesum = 0;int byteread = 0;while ((byteread = in.read(buffer)) != -1) {bytesum += byteread;out.write(buffer, 0, byteread); // 文件写操作}} catch (IOException ioe) {ioe.printStackTrace();} finally {try {out.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return file;}

以上就是文件与base64与字符串之间的转换,第一次写博客,写的不是很好,希望对大家有点帮助。

0 0
原创粉丝点击