HTML5定义了FileReader作为文件API的重要成员用于读取文件,FileReader接口提供了读取文件的方法和包含读取结果的事件模型。
关于FileReader的使用的每个api的使用,在这里就不说明了,想知道的可以转向这里 http://http://blog.csdn.net/vinifoxmailcom/article/details/50218789
这里主要说明它在说上传文件方面的案例
思路: 利用FileReader获取文件并进行Base64编码 , 保存编码并提交到服务器 , 服务获取到上传的Base64编码后,对其进行解码, 还原成文件,并保存在服务器
---jsp页面读取文件,并进行Base64编码 , 我在这里保存了文件名并传递到服务器,方便服务器做处理
<input type="file" id="fileup" class="validate[funcCall[file_format]]"/>
<input type="hidden" id="str_file" name="str_file"/>
<input type="hidden" id="file_name" name="file_name"/>
$("#fileup").change(function(){
var v = $(this).val();
var reader = new FileReader();
reader.readAsDataURL(this.files[0]);
reader.onload = function(e){
//console.log(e.target.result);
$("#str_file").val(e.target.result);
};
});
----服务器接受到Base64码字符串, 针对此字符串进行处理 , 解码成byte[] , 在利用文件流写文件
//获取file base64字符串
String str_file = request.getParameter("str_file");
//FileReader编码的Base64码前面有一段标示符, 在解码前需要去掉
String file_base64 = str_file.replace("data:application/msword;base64,", "");
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] b = decoder.decodeBuffer(file_base64);
// 生成路径
String strDirPath = request.getSession().getServletContext().getRealPath("/")+file_name;
File savefile = new File(strDirPath);
if (!savefile.getParentFile().exists())
{
savefile.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(strDirPath);
out.write(b);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}