标签:
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <!DOCTYPE HTML> 3 <html> 4 <head> 5 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 7 <title>ajax文件上传的开发</title> 8 <meta name="keywords" content="" /> 9 <meta name="description" content="" /> 10 <!-- 11 <link rel="stylesheet" type="text/css" href="styles.css"> 12 --> 13 <style type="text/css"> 14 #percent{width:600px;height:30px;position:relative;border:1px solid green;} 15 #percent #per{height:30px;background:green;position:absolute;left:0;top:0;} 16 </style> 17 </head> 18 19 <body> 20 <form action="upload/uploadAction.jsp?dirpath=pipi" method="post" enctype="multipart/form-data"> 21 <a href="javascript:;" class="uploadbtn" onclick="openFileDialog()">文件上传</a> 22 <input type="file" name="file" id="file" onchange="uploadFile()" style="display: none;" /> 23 <input type="submit" value="提交" /> 24 </form> 25 26 <img id="showImg" width="160" height="120" /> 27 <ul id="showlist"> 28 29 </ul> 30 31 32 <div id="percent"> 33 <div id="per"></div> 34 </div> 35 <div id="pnum"></div> 36 <script type="text/javascript"> 37 function openFileDialog(){ 38 var ie = navigator.appName == "Microsoft Internet Explorer"?true:false; 39 if(ie){ 40 //如果是ie浏览器 41 document.getElementById("file").click(); 42 }else{ 43 //自定义事件es5中的内容 44 var a = document.createEvent("MouseEvents"); 45 a.initEvent("click",true,true); 46 document.getElementById("file").dispatchEvent(a); 47 } 48 }; 49 50 51 52 //ajax文件上传 不支持低版本浏览器 53 function uploadFile(){ 54 //拿到文件上传的队列 55 var files = document.getElementById("file").files 56 var file = files[0]; 57 58 var type = file.type;//文件类型 59 var name = file.name;//文件名称 60 var size = file.size;//文件大小 61 if(type.indexOf("image") == -1) { 62 alert("请上传图片类型") 63 return; 64 } 65 //alert(file.name+"===="+file.size+"==="+file.type); 66 showImage(file,function(data){ 67 document.getElementById("showImg").src=data; 68 }) 69 70 var form = new FormData(); 71 form.append("file",file); 72 73 //如何传输给服务器端,进度条 74 var xhr = new XMLHttpRequest(); 75 //请求服务器 76 xhr.open("post", "upload/uploadAction.jsp?dirpath=pipi",true); 77 xhr.onreadystatechange = function(){ 78 if(this.readyState == 4 && this.status == 200){ 79 var data = this.responseText; 80 81 var jsonData = eval("("+data+")"); 82 var html = ""; 83 for(var i=0;i<jsonData.length;i++){ 84 html += "<li>"+jsonData[i].name+"===="+jsonData[i].sizeString+"====<img src=‘"+jsonData[i].url+"‘ width=‘50‘ height=‘50‘/>" 85 } 86 console.log(data); 87 document.getElementById("showlist").innerHTML += html; 88 } 89 }; 90 91 xhr.upload.addEventListener("progress", progressFunction,false); 92 xhr.send(form); 93 94 } 95 96 //进度条 97 function progressFunction(evt){ 98 console.log("------"); 99 var perDom = document.getElementById("per"); 100 if(evt.lengthComputable){ 101 //evt.loaded已经上传了多少 102 //event.total上传文件的总大小 103 var p = evt.loaded / event.total; 104 console.log(p); 105 var pnum = Math.floor(p*100) +"%"; 106 perDom.style.width = pnum; 107 document.getElementById("pnum").innerHTML = pnum; 108 } 109 } 110 111 /*图片预览*/ 112 function showImage(f,callback){ 113 var reader = new FileReader(); 114 reader.onload = (function(theFile) { 115 return function(e) { 116 // img 元素 117 if(callback)callback(e.target.result); 118 }; 119 120 })(f); 121 reader.readAsDataURL(f); 122 }; 123 124 </script> 125 </body> 126 </html>
1 <%@page import="org.apache.struts2.json.JSONUtil"%> 2 <%@page import="com.rui.util.StrUtils"%> 3 <%@page import="java.io.File"%> 4 <%@page import="org.apache.commons.fileupload.FileItem"%> 5 <%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%> 6 <%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%> 7 <%@page import="org.apache.commons.fileupload.FileItemFactory"%> 8 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 9 <% 10 11 /*文件上传的方式*/ 12 13 //1.获取文件上传的工厂类 14 FileItemFactory factory = new DiskFileItemFactory(); 15 //2.解析上传文件的工厂 16 ServletFileUpload fileUpload = new ServletFileUpload(factory); 17 //3.通过解析类解析request对象中的二进制文件 18 List<FileItem> fileItems = fileUpload.parseRequest(request); 19 //4.读取二进制文件,写入服务器 20 21 //获取服务器的路径getRealPath()获取当前项目所在服务器的根目录 22 //D:\tool\dev\apache-tomcat-7.0.56-windows-x86\apache-tomcat-7.0.56\me-webapps\fileUpload\resource 23 String dirpath = request.getParameter("dirpath");// 24 if(StrUtils.isEmpty(dirpath)) dirpath = "default"; 25 String fpath = "resource/"+dirpath; 26 String path = request.getRealPath(fpath); 27 File rootPath = new File(path); 28 //如果目录不存在就动态创建 29 if(!rootPath.exists()){ 30 rootPath.mkdirs(); 31 } 32 33 //如果有文件,就开始进行读和写 34 if(fileItems != null && fileItems.size()>0){ 35 List<Map<String,Object>> maps = new ArrayList<Map<String,Object>>(); 36 for(FileItem fileItem : fileItems){ 37 if(!fileItem.isFormField()){//判断是不是file表单 38 //获取文件名称 39 String filename = fileItem.getName(); 40 //文件大小 41 long filesize = fileItem.getSize(); 42 //获取文件后缀 43 String ext = StrUtils.getExt(filename, true); 44 //重构文件的名称===头像上传的原理就是文件的覆盖 45 String fname = UUID.randomUUID().toString()+ext; 46 File fileName = new File(rootPath,fname); 47 fileItem.write(fileName); 48 49 Map<String,Object> map = new HashMap<String,Object>(); 50 map.put("name", filename); 51 map.put("size", filesize); 52 map.put("sizeString", StrUtils.countFileSize(filesize)); 53 map.put("url", fpath+"/"+fname); 54 maps.add(map); 55 56 } 57 } 58 out.print(JSONUtil.serialize(maps)); 59 }else { 60 out.print(""); 61 //response.sendRedirect("fail.jsp"); 62 } 63 //5.在服务器创建一个上传的目录 64 //6.开始写入 65 //7.返回数据 66 67 //response.sendRedirect("success.jsp"); 68 69 %>
标签:
原文地址:http://www.cnblogs.com/sun-rain/p/4907037.html