首页 > 代码库 > 图片上传代码
图片上传代码
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="http://www.mamicode.com/imageupload.css" /><script type=‘text/javascript‘ src=http://www.mamicode.com/‘/Qpid/dwr/engine.js‘></script>"text/javascript" src="http://www.mamicode.com/scripts/jquery.min.js"></script><script type=‘text/javascript‘ src=http://www.mamicode.com/‘/Qpid/dwr/util.js‘></script>"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 = http://www.mamicode.com/reader.result;"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"; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。