浏览 6029 次
锁定老帖子 主题:html5 图片上传范例详解
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2013-01-07
代码如下: 前台的jsp如下: <%@ page language="java" pageEncoding="UTF-8"%> <%@ page isELIgnored="false"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+ path + "/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>我的webQQ</title> <base href="<%=basePath%>"/> <script type="text/javascript" src="<%=basePath%>js/jquery-1.6.1.min.js"></script> <script language="JavaScript" type="text/JavaScript"> $(function(){ if (window.FileReader) { var file ; var list = document.getElementById('list'), cnt = document.getElementById('container'), btn = document.getElementById("upLoadbtn"); // 判断是否图片 function isImage(type) { switch (type) { case 'image/jpeg': case 'image/png': case 'image/gif': case 'image/bmp': case 'image/jpg': return true; default: return false; } } function looks(f,img){ list.innerHTML += '<li><strong>' + f.name + '</strong> - ' + f.size + ' bytes<p>' + img + '</p></li>'; cnt.innerHTML = img; } // 处理拖放文件列表 function handleFileSelect(evt) { evt.stopPropagation(); evt.preventDefault(); var files = evt.dataTransfer.files; for (var i = 0, f; f = files[i]; i++) { var t = f.type ? f.type : 'n/a'; reader = new FileReader(); isImg = isImage(t); // 处理得到的图片 if (isImg) { reader.onload = (function (theFile) { return function (e) { img = '<img class="preview" src="' + e.target.result + '" title="' + theFile.name + '"/>'; looks(theFile, img); file=theFile; }; })(f); reader.readAsDataURL(f); } else { img = '"o((>ω< ))o",你传进来的不是图片!!'; looks(f, img); } } } // 处理插入拖出效果 function handleDragEnter(evt){ this.setAttribute('style', 'border-style:dashed;'); } function handleDragLeave(evt){ this.setAttribute('style', ''); } // 处理文件拖入事件,防止浏览器默认事件带来的重定向 function handleDragOver(evt) { evt.stopPropagation(); evt.preventDefault(); } cnt.addEventListener('dragenter', handleDragEnter, false); cnt.addEventListener('dragover', handleDragOver, false); cnt.addEventListener('drop', handleFileSelect, false); cnt.addEventListener('dragleave', handleDragLeave, false); function upload(){ var container = document.getElementById('container'); /** //获取分割线 var boundary="----------BOUNDARY"+(new Date()).getTime(); //新建文件读取 var fileReader = new FileReader(); //读取文件 fileReader.readAsBinaryString(file); var fileData = fileReader.result; //拼接body var body = ''; body += "--" + boundary + "\r\n"; body += "Content-Disposition: form-data; name=\"image\"; filename=\"" + file.name + "\"\r\n"; body += "Content-Type: "+file.type+"\r\n\r\n"; body += fileData + "\r\n"; body += "--" + boundary + "--\r\n"; //开始异步请求 var xhr = new XMLHttpRequest(); xhr.open('POST', "test/upload.html", true); xhr.setRequestHeader('content-type', "multipart/form-data, boundary="+boundary); xhr.setRequestHeader("Content-Length",file.size); alert(body); xhr.sendAsBinary(body); */ var xhr = new XMLHttpRequest(); xhr.open('post', "test/upload.html", true); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); var fd = new FormData(); fd.append('name', file.name); // Add file data fd.append('file', file); // Send data xhr.send(fd); /** xhr.onload = function() { alert("onload"); }; xhr.onerror = function() { //alert(this.responseText); }; xhr.upload.onprogress = function(event) { //alert("onprogress"); }; xhr.upload.onloadstart = function(event) { //alert("start"); }; // prepare FormData var formData = new FormData(); formData.append('myfile', file); xhr.send(formData); */ } btn.addEventListener('click',upload,false); } else { document.getElementById('section').innerHTML = '你的浏览器不支持啊,同学'; } }); </script> <style> #section{font-family: "Georgia", "微软雅黑", "华文中宋";} .container{display:inline-block;min-height:200px;min-width:360px;color:#f30;padding:30px;border:3px solid #ddd;-moz-border-radius:10px;-webkit-border-radius:10px;border-radius:10px;} .preview{max-width:360px;} #files-list{position:absolute;top:0;left:500px;} #list{width:460px;} #list .preview{max-width:250px;} #list p{color:#888;font-size:12px;} #list .green{color:#09c;} </style> </head> <body> <div id="section"> <p>把你的图片拖到下面的容器内:</p> <div id="container" class="container"> </div> <div id ="files-list"> <p>已经拖进过来的文件:</p> <ul id="list"></ul> </div> <input type="button" value = "确认上传" id="upLoadbtn" "/> </div> </body> </html> 后台的java代码如下: /** * * @author 程欣伟 * 图片上传 * @param request */ @RequestMapping("upload.html") public void upload(HttpServletRequest request) { try { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; //获取文件map信息 Map<String,MultipartFile> fileMap = multipartRequest.getFileMap(); //迭代map Iterator<Entry<String,MultipartFile>> iterator = fileMap.entrySet().iterator(); while(iterator.hasNext()){ Map.Entry<String,MultipartFile> entry = iterator.next(); //获取文件信息 MultipartFile value = entry.getValue(); //获取文件大小 Long size = value.getSize(); //获取文件名字 String fileName = value.getOriginalFilename(); //获取后缀名 String houzhuiName = fileName.substring(fileName.lastIndexOf('.')+1,fileName.length()); BufferedOutputStream out = null; BufferedInputStream in = null; //获取文件字节数组 byte[] b = value.getBytes(); try { String filename = UUID.randomUUID().toString(); // 重命名文件 String dir = "d:/image/"; File file = new File(dir); if(!file.exists()){ file.mkdir(); } String filepathString = dir+filename+"."+houzhuiName; //吧字节数组 写入 out = new BufferedOutputStream(new FileOutputStream(filepathString, true)); out.write(b, 0, b.length); } catch (Exception ex) { // TODO: handle exception } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } } } catch (Exception ex) { ex.printStackTrace(); } } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2013-05-22
你这个代码在chome测试通过么?chrome不支持XMLHttpRequest的sendAsBinary方法吧
|
|
返回顶楼 | |