ajax文件异步上传文件,后台request获取上传的文件流
发布时间:2020-12-16 02:05:00 所属栏目:百科 来源:网络整理
导读:一、先看后台servlet代码,使用的是 org. apache. commons. fileupload. servlet.ServletFileUpload 组件封装的文件(否则自己处理request.inputStream很麻烦) ServletFileUpload upload = new ServletFileUpload(); try { List? items = upload.parseReques
一、先看后台servlet代码,使用的是
org.
apache.
commons.
fileupload.
servlet.ServletFileUpload 组件封装的文件(否则自己处理request.inputStream很麻烦)
ServletFileUpload upload = new ServletFileUpload();
try { List<?> items = upload.parseRequest(request); Iterator iter = items.iterator(); while(iter.hasNext()){ FileItem item = (FileItem) iter.next(); if (item.isFormField()) { //如果是普通表单字段 String name = item.getFieldName(); String value = item.getString(); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); File uploadedFile = new File("E:/Downloads/upload/" + fileName); try { item.write(uploadedFile); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } catch (FileUploadException e) { e.printStackTrace(); }
二、前台的html和js代码
0.html页面引入一个js,些js内容见下面。
1.html页面中要加一个label 控件:<label id="fileup_id" >选择图片</label>。
2.在html页面的onload事件中加如下代码:
asy.init({
url : "/hbnpc/system/activity/activityUpload",//上传的路径 filename : "pic_na",//上传的字段名 target : "fileup_id",//上传按钮的id complete : afile//回调函数 });
三、引入的js内容
/** *文件异步上传工具 * */ var asy = {}; asy.init = function(args){ asy.args = args; var id = "asy_input_file" + new Date(); var fileinput = document.createElement("input"); asy.fileinput = fileinput; fileinput.type = "file"; fileinput.id = id; fileinput.name = args.filename; fileinput.onchange = asy.upload; fileinput.style.cssText = 'position:absolute; top:-9999px; left:-9999px'; document.body.appendChild(fileinput); var label = document.getElementById(args.target); asy.label = label; label.setAttribute("for",id); //$(label).attr("for",id); //如果要兼容ie7 放开这句 } asy.upload = function(){ var form = document.createElement("form"); asy.form = form; form.action = asy.args.url; form.method = "post"; form.encoding = "multipart/form-data"; form.appendChild(asy.fileinput); var frame = document.createElement("iframe"); frame = document.body.appendChild(frame); asy.frame = frame; frame.src = asy.args.url; //frame.contentWindow.document.body.appendChild(asy.form);//不兼容ie frame.style.cssText = 'position:absolute; top:-9999px; left:-9999px'; setTimeout(function(){ frame.contentWindow.document.body.appendChild(asy.form); frame.onload = function(){ asy.args.complete(this.contentWindow.document.body.outerText);//textContent//不兼容ie asy.clear(); } asy.form.submit(); },100); } asy.clear = function(){ document.body.removeChild(asy.frame); asy.init(asy.args); }
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |