简单的图片上传功能实现:
页面JSP:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page contentType="text/html;charset=UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta name="Generator" content="EditPlus">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>首页</title>
<link rel="stylesheet" type="text/css" href="${ctx }/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="${ctx }/themes/icon.css">
<title></title>
</head>
<body style="background-color: #E1ECFF">
<div>
<div>文件上传:</div><br>
<div>
<img id="photo" alt="" src="${ctx }/images/1507774341468.jpg"
style="width:200px;height:260px;">
<br><br>
<input id="changeFile" type="file" style="width:200px;height: 30px;"
accept="image/gif,image/jpeg,image/jpg">
</div>
</div>
</body>
<script type="text/javascript" src="${ctx }/js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="${ctx }/js/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${ctx }/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript">
$(function(){
var path,clip = $("#photo"),FileReader = window.FileReader;
$("#changeFile").change(function() {
if (FileReader) {//chrome浏览器处理
var reader = new FileReader(),
file = this.files[0];
reader.onload = function(e) {
clip.attr("src", e.target.result);//这里是把图片转成64位数据存入<img>中的src里
};
reader.readAsDataURL(file);
//这里需要延迟一下,否则无法放入文本框内
setTimeout("showchange()",1000);
}
else {//其他浏览器处理,火狐在这里就不写出来了,网上资料很多
path = $(this).val();
if (/"\w\W"/.test(path)) {
path = path.slice(1,-1);
}
clip.attr("src",path);
}
});
});
//存入照片数据
function showchange(){
var base64ImageData = $("#photo").attr("src");
//获取当前的系统时间
var time = new Date().getTime();
$.ajax({
url:"${ctx}/account/saveImage.do",
type:"post",
data:{"base64ImageData":base64ImageData,"time":time},
dataType:"json",
success:function(result){
window.parent.$.messager.alert('信息',"保存成功!", "info");
},
error:function(){
window.parent.$.messager.alert('信息',"请求失败!", "error");
}
});
}
</script>
</html>
后端的处理:
后端主要处理了图片,是否保存的问题。将图片转换成转成64位数据,通过ajax传到后台中进行处理。
@RequestMapping("/saveImage.do")
@ResponseBody
public Map<String,String> saveImage() throws Exception{
HttpServletRequest request = ((ServletRequestAttributes)
RequestContextHolder.getRequestAttributes()).getRequest();
//获取64位的数据
String base64ImageData = request.getParameter("base64ImageData");
//获取当前时间,作为图片的命名
String time = request.getParameter("time");
String subStringBase64 = base64ImageData.substring(base64ImageData.indexOf("base64,")+7);
System.out.println(subStringBase64);
String path = AccountController.class.getResource("/").getFile().
replace("WEB-INF/classes/", "").substring(1)+"images/"+time+".jpg";
System.out.println(path);
Map<String,String> map = new HashMap<String, String>();
boolean b = GenerateImage(subStringBase64,path);
if(b){
map.put("result", "success");
}else{
map.put("result", "error");
}
return map;
}
// 对字节数组字符串进行Base64解码并生成图片
public static boolean GenerateImage(String imgStr, String imgFilePath) {
if (imgStr == null) // 图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] bytes = decoder.decodeBuffer(imgStr);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
// 生成jpeg图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}