h5 FileReader 上传文件

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();  
		    }

转载于:https://my.oschina.net/u/2258281/blog/1558721

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值