ajaxFileUpload.js 实现异步文件上传

0 篇文章 0 订阅

使用iquery的插件ajaxFileUpload.js实现文件的异步上传。后台为java

1.在页面中引入jquery.js和ajaxFileUpload.js,切记jquery.js要在ajaxFileUpload.js之前。

2. html页面代码

<div id="wait_loading" style="display:none;">
    <div style="width:103px;margin: 0 auto;padding-top:200px;"><img src="<%=path %>/images/loading.gif"/></div>
</div>
<div id="edit_div">
     <div class="edit_content">
		  <div class="current_pos">
			  <span style="margin-left:20px;font-size: 15px; font-weight: bold;color:#eee;">上传检测文件</span>
			  <div class="close_icon">
				<a href="#" onClick="closeDiv()">
					<i class="glyphicon glyphicon-remove"></i>
				</a>
			 </div>
		</div>
		 <div class="main_upload col-md-12" >
		    <span class="col-md-3">选择上传文件:</span>
		    <div class="col-md-7 file_input"><input type="file" id="upload_file" name="upload_file" /></div>
		    <input  type="button" value="上传" οnclick="commit()"/>
		 </div>
    </div>
</div>
3.javascript代码


function closeDiv(){
	document.getElementById("edit_div").style.display="none";
}	
function showDiv(){
	document.getElementById("edit_div").style.display="block";
}
function commit(){
    document.getElementById("edit_div").style.display="none";
    $("#wait_loading").ajaxStart(function() {
        $(this).show();
    // 文件上传完成将div隐藏起来
    }).ajaxComplete(function() {
        $(this).hide();
    });
    //console.log("uploading");
    
    if ($("#upload_file").val().length > 0) {
        ajaxFileUpload();
    }
    else {
         alert("请选择要上传的文件!!");
         document.getElementById("edit_div").style.display="block";
    }	  
}	
function ajaxFileUpload(){   
   $.ajaxFileUpload({
        url:"<%=basePath%>FileUploadServlet", 
        type: "post",
        secureuri: false, //一般设置为false
        fileElementId: 'upload_file', // 上传文件的id、name属性名   
        success: function(data, status){  
            alert("上传成功!");  
            location.reload();
        },
        error: function(data, status, e){ 
            alert(e);
        }
    });	
}
4.后台Servlet代码
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException,IOException {

	String fileName = "";
	//boolean isMultipart = ServletFileUpload.isMultipartContent(req);
		
	DiskFileItemFactory factory = new DiskFileItemFactory();  		
	// Configure a repository (to ensure a secure temp location is used)  
        ServletContext servletContext = req.getSession().getServletContext();  
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");  
        factory.setRepository(repository); 
        System.out.println("-----------------uploading");
        // Create a new file upload handler  
        ServletFileUpload upload = new ServletFileUpload(factory); 
        upload.setHeaderEncoding("UTF-8");//解决中文乱码 
        try {  
            List<FileItem> items = upload.parseRequest(req);  
            for(FileItem item : items) {  
                //其他参数  
                String type = item.getContentType();  
                if(type == null) {  
                   //System.out.println(item.getString(item.getFieldName()));  
                    continue;  
                }                    
                //文件参数  
                fileName = item.getName();   
                               
                //设置保存文件路径  
                String realPath = this.getServletContext().getRealPath("/upload");
                //System.out.println("-----------------realPath--"+realPath);
                File dir = new File(realPath); 
                
                // System.out.println("-----------------filename--"+fileName);
                
                if (!dir.exists() && !dir.isDirectory()) {
                    System.out.println(realPath+"目录不存在,需要创建");
                    //创建目录
                    dir.mkdir();
                }
                
                File f = new File(dir, fileName);   
                f.createNewFile();                    
                //保存  
                item.write(f);              	
                resp.getWriter().print("success");
            }  
        }catch (FileUploadException e) {  
            e.printStackTrace();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }          	
}


本程序实现了点击按钮弹出选择上传文件的对话框,选定文件后,上传过程序中会有一个等待图片.gif 显示。

后出现问题,ajax里的data在带其他参数,后台接收不到,值为NULL,需修改ajaxfileUpload.js文件,可参考http://blog.csdn.net/u013243986/article/details/51497057



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值