client页面上传到上传到服务器并且在服务器保存
xhtml页面
<?xml version="1.0" encoding="UTF-8" ?> <!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> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Insert title here</title> <link rel="stylesheet" type="text/css" href="imageupload.css" /> <script type=‘text/javascript‘ src=‘/Qpid/dwr/engine.js‘></script> <script type=‘text/javascript‘ src=‘/Qpid/dwr/interface/ProfileBeanMock.js‘></script> <script type="text/javascript" src="scripts/jquery.min.js"></script> <script type=‘text/javascript‘ src=‘/Qpid/dwr/util.js‘></script> <script type="text/javascript"> var byteimage; function copyText(){ //alert("dasdas"); ProfileBeanMock.saveImage(byteimage, callback); } function callback(data){ // alert(data); window.opener.location.reload(); window.close(); } $(document).ready(function () { var fileInput = document.getElementById(‘fileInput‘); var fileDisplayArea = document.getElementById(‘fileDisplayArea‘); fileInput.addEventListener(‘change‘, function(e) { // Put the rest of the demo code here. var file = fileInput.files[0]; var imageType = /image.*/; if (file.type.match(imageType)) { var reader = new FileReader(); reader.onload = function(e) { fileDisplayArea.innerHTML = ""; // Create a new image. var img = new Image(); // Set the img src property using the data URL. img.src = reader.result; byteimage=reader.result; // Add the image to the page. fileDisplayArea.appendChild(img); } reader.readAsDataURL(file); } else { fileDisplayArea.innerHTML = "File not supported!"; } }); });//$(document) </script> </head> <body> <div id="page-wrapper"> <h1>Image File Reader</h1> <div> Select an image file: <input type="file" id="fileInput"></input> <button onclick="copyText()">Copy Text</button> </div> <div id="fileDisplayArea"></div> </div> </body> </html>
这里用到了dwr框架,主要是异步将图片传入server的javabean中,js不能访问到client机器上图片的真实路径,所以要用到FileReader()这个对象。服务器端的主要功能是将图片的data URL流变成图片然后保存,具体代码:
public String saveImage(String imagebyteString) { String encodingPrefix = "base64,"; int contentStartIndex = imagebyteString.indexOf(encodingPrefix) + encodingPrefix.length(); byte[] decodedBytes = DatatypeConverter .parseBase64Binary(imagebyteString.substring(contentStartIndex)); try { BufferedImage bfi = ImageIO.read(new ByteArrayInputStream( decodedBytes)); String nameString = UUID.randomUUID().toString() + ".png"; File outputfile = new File(nameString); this.userPhotoUrl = outputfile.getCanonicalPath(); ImageIO.write(bfi, "png", outputfile); bfi.flush(); } catch (IOException e) { e.printStackTrace(); return "false"; } return "success"; }
原文:http://www.cnblogs.com/j3eee/p/3815954.html