后台是使用servlet 的
前台页面需要导入的js库有:
jquery.uploadify.v2.1.4.js
swfobject.js
uploadify.css
需要提交的form页面:companyEdit.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/pages/common/taglibs.jsp"%>
<html>
<head>
<title></title>
<%@ include file="/WEB-INF/pages/common/metas.jsp" %>
<script charset="utf-8" src="${ctx}/js/editor/kindeditor.js"></script>
<script src="${ctx}/js/function.js" type="text/javascript"></script>
<style>
.ebody table {
margin-bottom: 0px;
margin-left: 10px;
margin-top: 0px;
width: 90%;
}
</style>
<script language="javascript" defer="defer">
$(function(){
$("#companyForm").validate( {
rules : {
loginId : {
"email":true,
required : true,
remote : "${ctx}/job/company/check.do?id=${entity.id}",
maxlength : 50
},
password : {
required : true,
maxlength : 100
},
companyName : {
required : true,
maxlength : 100
},
phone:{
"phone": true,
required : true
} ,
expiration : {
required :true
},
advanceType:"required",
isIntegrity:"required"
},
messages : {
loginId : {
"eamil": "只能为邮箱!",
required : "用户名不能为空!",
remote : jQuery.format("{0} 已经存在!"),
maxlength : "长度不能超过50个字"
},
password : {
required : "密码不能为空!",
maxlength : "长度不能超过100个字"
},
companyName : {
required : "公司名称不能为空!",
maxlength : "长度不能超过100个字"
},
phone:{
"phone":"请输入正确的手机号码",
required : "请输入正确的手机号码!",
required : "手机号码不能为空"
} ,
expiration : {
required : "到期时间不能为空!"
},
isIntegrity:"请选择资料是否完成",
advanceType:"请选择用户类型",
},
errorPlacement : function(error, element) {
element.parent().find("#error").replaceWith(error);
},
submitHandler : function() {
var path = $("#facePath").val();
if(path !="0"){
$.ajax( {
type : "POST",
url : '${ctx}/url/upload',// 需要链接到服务器地址
fileElementId : 'uploadify',// 文件选择框的id属性
dataType : 'json',// 服务器返回的格式,可以是json
data:{
"operation":2,
"x1":$('#x1').val(),
"x2":$('#x2').val(),
"y1":$('#y1').val(),
"y2":$('#y2').val(),
"iocPath":"companyIoc",
"path":path
},
success : function(result) {
if(result.result ==1){
document.getElementById("avatar").value=result.avatar;
$.ajax({
url : "${ctx}/job/company/save.do",
type : "POST",
dataType : "json",
data : $("#companyForm").serialize(),
timeout : 500000,
error : function() {
ymPrompt.alert("系统异常!");
},
success : function(data) {
ymPrompt.alert("修改成功!");
if (data.status) {
setTimeout(function() {
location.href="${ctx}/job/company/list.do";
}, 1000);
} else {
return;
}
}
});
}else{
ymPrompt.alert("图片上传异常!");
}
},
error:function(data) {
ymPrompt.alert("修改成功!");
}
});
}else{
//addForm("${ctx}/hospital/doctor/save.do", "#doctorForm");
$.ajax({
url : "${ctx}/job/company/save.do",
type : "POST",
dataType : "json",
data : $("#companyForm").serialize(),
timeout : 500000,
error : function() {
ymPrompt.alert("系统异常!");
},
success : function(data) {
ymPrompt.alert(data.msg);
if (data.status) {
location.href="${ctx}/job/company/list.do";
} else {
return;
}
}
});
}
}
});
$("#groupBtn").live("click",function(){
var url ='${ctx}/system/userGroup/findKeyAndValue.do';
ymPrompt.win(
{title:'获取用户组',
width:700,
height:400,
fixPosition:true,
maxBtn:true,
minBtn:true,
autoClose:true,
iframe:{
id:'myId',name:'myName',
src:url}
});
});
$(".choose").live("click",function(){
var url =$(this).attr("hhref");//+"?hospitalId="+$("#hospitalId").val()+"&haeptId="+$("#haeptId").val();
var title=$(this).attr("title");
ymPrompt.win({
message:url,
width:580,
height:420,
title:title,
handler:null,
maxBtn:true,
minBtn:true,
iframe:true
});
});
$("#removePro").live('click',function(){
$("#provinceId").attr("value","");
$("#provinceName").attr("value","");
})
$("#removeBtn").live('click',function(){
$("#groupUser").attr("value","");
$("#queryGroupId").attr("value","");
})
$("#removeDoctor").live('click',function(){
$("#doctorName").attr("value","");
$("#doctorId").attr("value","");
})
if(${entity.id ==null}){
}else{
}
});
KE.show( {
id : 'signature',
width :"90%",
height:"200px",
resizeMode : 1,
allowFileManager : false,
allowPreviewEmoticons : false,
allowUpload : true,
items : [ 'fontname', 'fontsize', '|', 'textcolor', 'bgcolor', 'bold',
'italic', 'underline', 'removeformat', '|', 'justifyleft',
'justifycenter', 'justifyright', 'insertorderedlist',
'insertunorderedlist', '|', 'emoticons', 'link' ],
afterCreate : function(id) {
KE.event.ctrl(document, 1, function() {
KE.util.setData(id);
document.forms['contentForm'].submit();
});
KE.event.ctrl(KE.g[id].iframeDoc, 1, function() {
KE.util.setData(id);
document.forms['contentForm'].submit();
});
}
});
</script>
</head>
<body>
<div class="main_content">
<div class="content_up_bg">
<span style="margin-left:10px">企业用户维护1</span>
</div>
<hr style="border: 1px #BFC0C0 solid;"/>
<form id="companyForm" name="companyForm" method="post" enctype="multipart/form-data">
<div class="ebody">
<input type="hidden" name="id" value="${entity.id}" />
<table width="60%" style="margin-top: 10px;">
<tr>
<td align="center" width="150px">
登录者账号:
</td>
<td align="left" >
<input type="text" size="30" id="loginId" ${'admin' eq entity.loginId ? 'readonly="readonly"':'' } name="loginId" value="${entity.loginId }"/>
<input type="hidden" name="email" value="${entity.email }" />
<font color="red">*</font>
<br />
<p id="error" />
</td>
<td align="center">
<span>密码:</span>
</td>
<td align="left">
<input type="password" style="width:200px" name="password"
<c:choose><c:when test="${ empty entity.password}"> maxlength="45" </c:when> <c:otherwise> minlength="6" maxlength="50" </c:otherwise></c:choose> value="${entity.password}"/>
<font color="red">*</font>
<br />
<p id="error" />
</td>
</tr>
<tr>
<td align="center">
公司名称:
</td>
<td align="left">
<input type="text" id="companyName" size="30" name="companyName"
maxlength="20" value="${entity.companyName}"/>
<font color="red">*</font><br />
<p id="error" />
</td>
<td align="center">
用户组:
</td>
<td align="left">
<div align="left">
<input type="text" name="groupName" value="${groupName}" readonly id="groupUser" />
<input type="hidden" name="groupId" value="${entity.groupId}" id="queryGroupId"/>
<a class="btnDel" href="javascript:void(0)" id="removeBtn">清空</a>
<a class="btnLook" href="javascript:void(0)" id="groupBtn" href="${ctx}">查找</a>
</div>
</td>
</tr>
<tr>
<td align="center">
是否有效:
</td>
<td align="left">
<div class="select_style">
<select id=status name="status" >
<option value="1" ${'1' eq entity.status ? 'selected="selected"' : ''}>
是
</option>
<option value="0" ${'0' eq entity.status ? 'selected="selected"' : ''}>
否
</option>
</select>
</div>
<font color="red">*</font>
<br />
<p id="error" />
</td>
<td align="center">
企业类型:
</td>
<td align="center">
<div class="select_style">
<select id=compType name="compType" >
<option selected>
--
请选择
--
</option>
<c:forEach items="${dicList}" var="dic">
<option value="${dic.id }" ${dic.id == entity.compType ? 'selected="selected"' : ''}>${dic.name }</option>
</c:forEach>
</select>
</div>
</td>
</tr>
<tr>
<td align="center">
联系地址:
</td>
<td align="left">
<input type="text" size="50" name="address"
value="${entity.address}" />
</td>
<td align="center">
企业网址:
</td>
<td align="left">
<input type="text" size="50" name="webSit"
value="${entity.webSit}" />
</td>
</tr>
<tr>
<td align="center">
注册时间:
</td>
<td align="left">
<input type="text" value="<fmt:formatDate value='${entity.joinDate }' type='date' pattern='yyyy-MM-dd HH:mm:ss'/>" name="joinDate" id="joinDate" size="12"
disabled="disabled" readonly="readonly"
/>
</td>
<td align="center">
到期时间:
</td>
<td align="left">
<input type="text" style="background:#fff url(${ctx }/js/date/skin/datePicker1.gif) no-repeat right;" size="30" value="<fmt:formatDate value='${entity.expiration }' type='date' pattern='yyyy-MM-dd HH:mm:ss'/>" id="expiration" name="expiration" maxlength="100"
readonly
class="readonly Wdate2" οnclick="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})"
size="12" />
<font color="red">*</font>
<br/>
<p id="error" />
</td>
</tr>
<tr>
<td align="center">
电话:
</td>
<td align="left">
<input type="text" size="50" name="phone"
value="${entity.phone}" />
<font color="red">*</font>
<br />
<p id="error" />
</td>
<td align="center">
传真:
</td>
<td align="left">
<input type="text" size="50" name="fax"
value="${entity.fax}" />
</td>
</tr>
<tr>
<td align="center">
用户类型:
</td>
<td align="left">
<div class="select_style">
<select id=advanceType name="advanceType" >
<option selected>
--
请选择
--
</option>
<option value="0" ${'0' eq entity.advanceType ? 'selected="selected"' : ''}>
普通用户
</option>
<option value="1" ${'1' eq entity.advanceType ? 'selected="selected"' : ''}>
普通付费用户
</option>
<option value="2" ${'2' eq entity.advanceType ? 'selected="selected"' : ''}>
VIP付费用户
</option>
</select>
</div>
<font color="red">*</font>
<br />
<p id="error" />
</td>
<td align="center">
资料是否完整:
</td>
<td align="left">
<div class="select_style">
<select id=isIntegrity name="isIntegrity" >
<option >
--
请选择
--
</option>
<option value="0" ${'0' eq entity.isIntegrity ? 'selected="selected"' : ''}>
是
</option>
<option value="1" ${'1' eq entity.isIntegrity ? 'selected="selected"' : ''}>
否
</option>
</select>
</div>
<font color="red">*</font>
<br />
<p id="error" />
</td>
</tr>
<tr>
<td align="center">
Logo文件路径:<input type="hidden" id="avatar" name="avatar" value="${entity.avatar}" />
</td>
<td align="left">
<%@ include file="/WEB-INF/pages/upload/imagreaSelectFile.jsp"%>
<font color="red">*</font>
<br />
<p id="error" />
</td>
<td><c:if test="${entity.avatar ne null}"><img src="${ctx }/attachFiles/companyIoc/${entity.avatar}"/> </c:if></td>
</tr>
<tr>
<td align="center">
公司描述:
</td>
<td align="left" colspan="3">
<textarea id="signature" οnfοcus="checkCharNumTextarea('signature',800,'false')" οnkeyup="checkCharNumTextarea('signature',800,'false')" name="signature" style="width:700px;height:200px; visibility: hidden;">
${entity.signature}</textarea>
<br />
<div style="color:#999999">当前字数 <font id="signature_txt" color="#FF0033"></font> 个/最多256个</div><p id="error" />
</td>
</tr>
</table>
</div>
<div align="center">
<input type="submit" class="button" value="提交" />
<input type="button" class="button" value="返回" οnclick="window.location='<c:url value='/job/company/list.do'/>'" />
</div>
</form>
</div>
</body>
</html>
导入的用于上传文件的jsp辅助页面:imagreaSelectFile.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<script language="javascript" defer="defer">
$(function(){
$("#uploadify").uploadify({
'uploader' : '${ctx}/js/uploadify/uploadify.swf',
'script' : '${ctx}/url/upload?iocPath=companyIoc',
'cancelImg' : '${ctx}/js/uploadify/cancel.png',
//'buttonImg' : '${ctx}/images/buttons/upload.jpg',
'queueID' : 'fileQueue',
'auto' : true,
'multi' : true,
'method' : 'post',
'simUploadLimit' : 100,
"queueSizeLimit" : 100,//允许选择文件的数量
'fileExt' : $("#fileType").val(),
'fileDesc' : '请选择*.jpg格式的文件', //允许上传的文件类型 ;必须先设置fileExt 属性再设置fileDesc
'scriptData' : '',
'onSelect': function(event, queueID, fileObj) {
},
'onComplete': function(event, ID, fileObj, response, datas) {
var data = $.parseJSON(response);
if (data['result'] == 1) {
$("#facediv").css({"display":"block"});
$("#face").attr("src",data.path);
$("#facePath").attr("value",data.path);
$('img#face').imgAreaSelect({
handles: true,
x1:0,y1:0,x2:100,y2:100,
onSelectChange: function (img, selection) {
var scaleX = 100 / (selection.width || 1);
var scaleY = 100 / (selection.height || 1);
$('#face + div > img').css({
width: Math.round(scaleX * 400) + 'px',
height: Math.round(scaleY * 300) + 'px',
marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
});
},
onSelectEnd: function (img, selection) {
$('#x1').val(selection.x1);
$('#y1').val(selection.y1);
$('#x2').val(selection.x2);
$('#y2').val(selection.y2);
}
});
}
},
'buttonText' : 'SELECT FILE'
});
});
</script>
<div id="uploadFile">
<input type="hidden" id="facePath" name="facePath" value="0" />
<input type="hidden" id="x1" name="x1" value="0" />
<input type="hidden" id="y1" name="y1" value="0" />
<input type="hidden" id="x2" name="x2" value="100" />
<input type="hidden" id="y2" name="y2" value="100" />
<input type='text' name='fileName' readonly value="${entity.avatar }" id='fileName' />
<input id="uploadify" name="uploadify" type="file" οnchange="fileName.value=this.value;" maxlength="100" style="display: none" />
</div>
<div id="facediv" style="display:none;z-index:100;">
<img id="face" height="150px"/>
</div>
<strong><span style="font-size:14px;">后台处理的servlet:FileUploadUrlServlet.java</span></strong>
public class FileUploadUrlServlet extends HttpServlet {
private static final long serialVersionUID = 5653610348191435218L;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
JSONObject result = new JSONObject();
String iocPath=request.getParameter("iocPath");//是公司头像的还是用户头像
String requestType = request.getContentType();
if (requestType != null && requestType.indexOf("multipart/form-data") != -1) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items;
try {
items = upload.parseRequest(request);
Iterator iter = items.iterator();
String webRoot = request.getSession().getServletContext()
.getRealPath("/");
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String suffix = item.getName().substring(item.getName().lastIndexOf("."));
String name = String.valueOf(System.currentTimeMillis());
StringBuffer sourcePath = new StringBuffer();
sourcePath.append(webRoot);
sourcePath.append(File.separator);
sourcePath.append("attachFiles\\"+iocPath+"\\big");
sourcePath.append(File.separator);
sourcePath.append(name);
sourcePath.append(suffix);
File imageFile= new File(sourcePath.toString());
if (!imageFile.getParentFile().exists()) {
imageFile.getParentFile().mkdirs();
}
item.write(imageFile);
result.put("result", 1);
result.put("attachId", 0l);
result.put("path", request.getContextPath()+"/attachFiles/"+iocPath+"/big/"+imageFile.getName());
}
}
response.getWriter().println(result);
} catch (FileUploadException e) {
response.getWriter().println("0");
e.printStackTrace();
} catch (Exception e) {
response.getWriter().println("0");
e.printStackTrace();
}
} else {
try{
Integer x1 = Integer.parseInt(request.getParameter("x1"));
Integer y1 = Integer.parseInt(request.getParameter("y1"));
Integer x2 = Integer.parseInt(request.getParameter("x2"));
Integer y2 = Integer.parseInt(request.getParameter("y2"));
String path = request.getParameter("path");
String fileName = path.substring(path.lastIndexOf("/")+1);
String suffix = fileName.substring(fileName.lastIndexOf("."));
String webRoot = request.getSession().getServletContext().getRealPath("/");
StringBuffer sourcePath = new StringBuffer();
sourcePath.append(webRoot);
sourcePath.append(File.separator);
sourcePath.append("attachFiles\\"+iocPath+"\\big");
sourcePath.append(File.separator);
sourcePath.append(fileName);
StringBuffer targetPath = new StringBuffer();
targetPath.append(webRoot);
targetPath.append(File.separator);
targetPath.append("attachFiles\\"+iocPath+"\\");
targetPath.append(File.separator);
targetPath.append(fileName);
cutImage(suffix.substring(1), sourcePath.toString(), targetPath.toString(),x1, y1, x2, y2);
AttachmentService attachmentService = (AttachmentService)AppUtil.getBean("attachmentService");
Attachment attachment = new Attachment();
attachment.setAttachmentPath(request.getRealPath("/")+"attachFiles\\"+iocPath+"\\");
attachment.setFileType("image/jpg");
attachment.setFileName(fileName);
attachment.setFileSize(2.0);
attachmentService.save(attachment);
result.put("avatar", fileName+"");
result.put("result", ""+1);
result.put("path",request.getContextPath()+"\\attachFiles\\"+iocPath+"\\"+fileName);
//new File(sourcePath.toString()).delete();
response.getWriter().println(result.toString());
} catch (Exception e) {
response.getWriter().println("0");
e.printStackTrace();
}
}
}
public static void cutImage(String suffix, String sourcePath, String targetPath,
int x1, int y1, int x2, int y2) throws IOException {
Image img;
ImageFilter cropFilter;
File sourceImgFile = new File(sourcePath);
//BufferedImage bi = compressImageFile(sourcePath);
BufferedImage bi= ImageIO.read(sourceImgFile);
int srcWidth = bi.getWidth();
int srcHeight = bi.getHeight();
int destWidth = x2 - x1;
int destHeight = y2 - y1;
if (srcWidth >= destWidth && srcHeight >= destHeight) {
Image image = bi.getScaledInstance(srcWidth, srcHeight,Image.SCALE_DEFAULT);
cropFilter = new CropImageFilter(x1, y1, destWidth, destHeight);
img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));
BufferedImage tag = new BufferedImage(destWidth, destHeight,BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
ImageIO.write(tag, suffix, new File(targetPath));
}
}
private static BufferedImage compressImageFile(String path) {
JFileChooser fileChooser = new JFileChooser(path);
File file = fileChooser.getSelectedFile();
BufferedImage bufferedImage = null;
file = new File(path);
if (null != file && file.exists()) {
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image srcImage = toolkit.getImage(file.getAbsolutePath()); // 构造Image对象
int wideth = -1;
int height = -1;
boolean flag = true;
while (flag) {
wideth = srcImage.getWidth(null); // 得到源图宽
height = srcImage.getHeight(null); // 得到源图长
System.out.println("wideth:" + wideth + " height:" + height);
if (wideth > 0 && height > 0) { // 因为 Toolkit.getImage 是异步读取,如果
// wideth 和 height
// 都大于0,表明图片已经加载完毕
// imageCanvas.setImage(srcImage);
flag = false;
} else {
try {
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 加载完毕,输出
int w = 1024;
float s = (float) wideth / 1024.0f;
int h = (int) ((float) height / s);
bufferedImage = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB);
}
return bufferedImage;
}
}