原创链接:http://www.cnblogs.com/yanqin/p/5345562.html
html代码 index.jsp(表单文件上传)
<form action="shangchuan.jsp" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="上传"> </form>
java 代码 : shangchuan.jsp
<%@page import="org.apache.struts2.json.JSONUtil"%> <%@page import="java.io.File"%> <%@page import="org.apache.commons.fileupload.FileItem"%> <%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%> <%@page import="org.apache.commons.fileupload.FileItemFactory"%> <%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); //设置上传文件大小 //long maxSize = 10 * 1024 * 1024; //upload.setSizeMax(maxSize); //拿到传过来的所有数据 List<FileItem> items = upload.parseRequest(request); List<Map<String,Object>> maps = new ArrayList<Map<String,Object>>(); //设置上传文件的路径 String path = request.getRealPath("resource/"+"123"); //遍历items for(FileItem item : items){ //判断是不是 普通表单元素 if(item.isFormField()){ /* 在form表单那里,将enctype设置成用二进制传输后,无法在用getPararmeter获得普通元素的值,要用如下方法。 //拿到 普通表单元素的名字 String name = item.getFieldName(); //判断是不是 我要的 表单元素 if(name.equals("username")){ String value = item.getString(); } */ }else{ //判断是不是真的上传文件了 if(item.getName()=="" || item.getSize() == 0){ return; }else{ //如果上传的目录不存在,就创建 File rootPath = new File(path); if(!rootPath.exists()){ rootPath.mkdirs(); } //获取上传文件的后缀 String fileName = item.getName(); String ext = getExt(fileName); long fileSize = item.getSize(); //生成文件名 String fname = UUID.randomUUID().toString()+ext; //上传文件 rootPath = new File(path,fname); item.write(rootPath); //返回这次上传的相关信息 String fpath = "resource/"+"123"; Map<String,Object> map = new HashMap<String,Object>(); map.put("name",fileName); map.put("size",fileSize); map.put("sizeString", fileSize+"字节"); map.put("url",fpath+"/"+fname); maps.add(map); } } out.print(JSONUtil.serialize(maps)); } %> <%! //根据名字 得出后缀名 public String getExt(String name){ return name.substring(name.lastIndexOf("."), name.length()); } %>
html代码,index.jsp ajax文件上传,带进度条
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <html> <head> <title></title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <style type="text/css"> * { padding: 0; margin: 0; } body { padding: 50px; } .uploadbtn { display: inline-block; padding : 20px 40px; border: 1px solid #ccc; border-radius: 4px; text-decoration: none; color: #666; padding: 20px 40px; } </style> </head> <body> <h1>不支持ie</h1> <br /> <br /> <br /> <br /> <br /> <form action="shangchuan.jsp" method="post" enctype="multipart/form-data"> <a href="javascript:void(0);" class="uploadbtn" onclick="openFileDialog()">文件上传</a> <!-- accept="image/*" 他的作用是限制上传文件的类型 --> <input type="file" name="file" id="file" onchange="uploadFile()"> <img src="" id="showimg"> </form> <br /> <br /> <br /> <br /> <div id="listBox"></div> <div id = "percent"></div> <script type="text/javascript"> function openFileDialog() { var ie = navigator.appName == "Microsoft Internet Explorer" ? true : false; if (ie) { //如果是ie document.getElementById("file").click(); } else { //自定义事件es5中的内容 var a = document.createEvent("MouseEvents"); a.initEvent("click", true, true); document.getElementById("file").dispatchEvent(a); } } function uploadFile() { var files = document.getElementById("file").files; var file = files[0]; //预览上传的文件 showImage(file, function(data) { document.getElementById("showimg").src = data; }) //html5 将文件装到表单里。 var form = new FormData(); form.append("file", file); //传输到服务端 var xhr = new XMLHttpRequest(); xhr.open("post", "shangchuan.jsp", true); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var data = this.responseText.trim(); var jsonData = eval("(" + data + ")"); var html = ""; for (var i = 0; i < jsonData.length; i++) { html += "<li>" + jsonData[i].name + "=====" + jsonData[i].sizeString + "</li>"+"<img width='50' height='50' src='"+jsonData[i].url+"'>"; } document.getElementById("listBox").innerHTML += html; } } //监听上传文件的进度 xhr.upload.addEventListener("progress",progressFunction,false); xhr.send(form); } //进度条 这里进度条没有美化,就显示的百分比。 function progressFunction(evt){ var percent = document.getElementById("percent"); if(evt.lengthComputable){ //evt.loaded已经上传多久了,event.total:上传文件的总大小 var p = evt.loaded / event.total; percent.innerHTML = Math.floor(p*100)+"%"; } } //图片预览 function showImage(f, callback) { var reader = new FileReader(); reader.onload = (function(theFile) { return function(e) { //img if (callback)callback(e.target.result); }; })(f); reader.readAsDataURL(f); } </script> </body> </html>