配置图片服务器的一部分参数
resource.properties:
#FTP\u76f8\u5173\u914d\u7f6e
#FTP\u7684ip\u5730\u5740
FTP_ADDRESS=192.168.3.27
FTP_PORT=21
FTP_USERNAME=ftpuser
FTP_PASSWORD=ftpuser
FTP_BASE_PATH=/www/images
#\u56fe\u7247\u670d\u52a1\u5668\u7684\u76f8\u5173\u914d\u7f6e
#\u56fe\u7247\u670d\u52a1\u5668\u7684\u57fa\u7840url
IMAGE_BASE_URL=http://192.168.3.27:8899/www/images
相关页面引入kindedtior的js
common.js:
Date.prototype.format = function(format){
var o = {
"M+" : this.getMonth()+1, //month
"d+" : this.getDate(), //day
"h+" : this.getHours(), //hour
"m+" : this.getMinutes(), //minute
"s+" : this.getSeconds(), //second
"q+" : Math.floor((this.getMonth()+3)/3), //quarter
"S" : this.getMilliseconds() //millisecond
};
if(/(y+)/.test(format)){
format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
}
for(var k in o) {
if(new RegExp("("+ k +")").test(format)){
format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
}
}
return format;
}; var TT = TAOTAO = {
// 编辑器参数
kingEditorParams : {
//指定上传文件参数名称
filePostName : "uploadFile",
//指定上传文件请求的url。
uploadJson : '/YouZhi-BackEng/pic/upload',
//上传类型,分别为image、flash、media、file
dir : "image"
},
// 格式化时间
formatDateTime : function(val,row){
var now = new Date(val);
return now.format("yyyy-MM-dd hh:mm:ss");
},
// 格式化连接
formatUrl : function(val,row){
if(val){
return "<a href='"+val+"' target='_blank'>查看</a>";
}
return "";
}, init : function(data){
// 初始化图片上传组件
this.initPicUpload(data);
// 初始化选择类目组件
this.initItemCat(data);
},
// 初始化图片上传组件
initPicUpload : function(data){
$(".picFileUpload").each(function(i,e){ //.picFileUpload
var _ele = $(e);
_ele.siblings("div.pics").remove();
_ele.after('\
<div class="pics" >\
\
</div>');
// 回显图片
if(data && data.pics){
var imgs = data.pics.split(",");
for(var i in imgs){
if($.trim(imgs[i]).length > 0){
_ele.siblings(".pics").find("ul").append("<li><a href='"+imgs[i]+"' target='_blank'><img src='"+imgs[i]+"' width='120' height='80' /></a></li>");
}
}
}
//给“上传图片按钮”绑定click事件
$(e).click(function(){
var form = $("#adForm");
//打开图片上传窗口
KindEditor.editor(TT.kingEditorParams).loadPlugin('multiimage',function(){
var editor = this;
editor.plugin.multiImageDialog({
clickFn : function(urlList) {
var imgArray = [];
KindEditor.each(urlList, function(i, data) {
imgArray.push(data.url);
form.find(".pictures").append("<input type='hidden' name='cpicture' value="+data.url+">");
form.find(".pics").append("<a href='"+data.url+"' target='_blank'><img src='"+data.url+"' width='904' height='336' /></a><br>");
});
form.find("[name=image]").val(imgArray.join(","));
editor.hideDialog();
}
});
});
});
});
}, // 初始化选择类目组件
initItemCat : function(data){
$(".selectItemCat").each(function(i,e){
var _ele = $(e);
if(data && data.cid){
_ele.after("<span style='margin-left:10px;'>"+data.cid+"</span>");
}else{
_ele.after("<span style='margin-left:10px;'></span>");
}
_ele.unbind('click').click(function(){
$("<div>").css({padding:"5px"}).html("<ul>")
.window({
width:'500',
height:"450",
modal:true,
closed:true,
iconCls:'icon-save',
title:'选择类目',
onOpen : function(){
var _win = this;
$("ul",_win).tree({
url:'/item/cat/list',
animate:true,
onClick : function(node){
if($(this).tree("isLeaf",node.target)){
// 填写到cid中
_ele.parent().find("[name=cid]").val(node.id);
_ele.next().text(node.text).attr("cid",node.id);
$(_win).window('close');
if(data && data.fun){
data.fun.call(this,node);
}
}
}
});
},
onClose : function(){
$(this).window("destroy");
}
}).window('open');
});
});
}, createEditor : function(select){
return KindEditor.create(select, TT.kingEditorParams);
}, /**
* 创建一个窗口,关闭窗口后销毁该窗口对象。<br/>
*
* 默认:<br/>
* width : 80% <br/>
* height : 80% <br/>
* title : (空字符串) <br/>
*
* 参数:<br/>
* width : <br/>
* height : <br/>
* title : <br/>
* url : 必填参数 <br/>
* onLoad : function 加载完窗口内容后执行<br/>
*
*
*/
createWindow : function(params){
$("<div>").css({padding:"5px"}).window({
width : params.width?params.width:"80%",
height : params.height?params.height:"80%",
modal:true,
title : params.title?params.title:" ",
href : params.url,
onClose : function(){
$(this).window("destroy");
},
onLoad : function(){
if(params.onLoad){
params.onLoad.call(this);
}
}
}).window("open");
}, closeCurrentWindow : function(){
$(".panel-tool-close").click();
}, changeItemParam : function(node,formId){
$.getJSON("/item/param/query/itemcatid/" + node.id,function(data){
if(data.status == 200 && data.data){
$("#"+formId+" .params").show();
var paramData = JSON.parse(data.data.paramData);
var html = "<ul>";
for(var i in paramData){
var pd = paramData[i];
html+="<li><table>";
html+="<tr><td colspan=\"2\" class=\"group\">"+pd.group+"</td></tr>"; for(var j in pd.params){
var ps = pd.params[j];
html+="<tr><td class=\"param\"><span>"+ps+"</span>: </td><td><input autocomplete=\"off\" type=\"text\"/></td></tr>";
} html+="</li></table>";
}
html+= "</ul>";
$("#"+formId+" .params td").eq(1).html(html);
}else{
$("#"+formId+" .params").hide();
$("#"+formId+" .params td").eq(1).empty();
}
});
},
getSelectionsIds : function (select){
var list = $(select);
var sels = list.datagrid("getSelections");
var ids = [];
for(var i in sels){
ids.push(sels[i].id);
}
ids = ids.join(",");
return ids;
}, /**
* 初始化单图片上传组件 <br/>
* 选择器为:.onePicUpload <br/>
* 上传完成后会设置input内容以及在input后面追加<img>
*/
initOnePicUpload : function(){
$(".onePicUpload").click(function(){
var _self = $(this);
KindEditor.editor(TT.kingEditorParams).loadPlugin('image', function() {
this.plugin.imageDialog({
showRemote : false,
clickFn : function(url, title, width, height, border, align) {
var input = _self.siblings("input");
input.parent().find("img").remove();
input.val(url);
input.after("<a href='"+url+"' target='_blank'><img src='"+url+"' width='80' height='50'/></a>");
this.hideDialog();
}
});
});
});
}
};
再自己写一个javascript:
<script type="text/javascript">
var itemAddEditor ;
//页面初始化完毕后执行此方法
$(function(){
//创建富文本编辑器
itemAddEditor = TAOTAO.createEditor("#adForm [name=desc]");
//itemAddEditor = KindEditor.create("#stepForm [name=desc]", TT.kingEditorParams);
//初始化类目选择和图片上传器
TAOTAO.init({fun:function(node){
TAOTAO.changeItemParam(node, "itemAddForm");
}});
});
</script>
在页面上的from表单中写入这个代码,引入上传组件:
<span class="pictures"></span>
<a href="javascript:void(0)"
class="easyui-linkbutton picFileUpload">
<span><input type="button" value="上传广告图片"></input></span> <br> <br>
</a>
<input type="submit" class="btn btn-default" value="提交">
<div hidden="true">
<textarea style="width:800px;height:300px;visibility:hidden;"
name="desc">
</textarea>
</div>
这个时候我们就可以看见页面上已经引入了一个文件上传组件
之后去后台编写controller和service
PictureController:
package com.youzhiback.controller; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; import com.youzhiback.service.IPictureService;
import com.youzhiback.utils.JsonUtils; @Controller
//图片上传controller
public class PictureController { @Autowired
private IPictureService pictureService; @RequestMapping("/pic/upload")
@ResponseBody
public String pictureUpload(MultipartFile uploadFile) {
Map result = pictureService.uploadPicture(uploadFile);
//为了保证功能的兼容性,需要把Result转换成json格式的字符串。
String json = JsonUtils.objectToJson(result);
return json;
}
}
PictureServiceImpl.java:
package com.youzhiback.service.impl; import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID; import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile; import com.youzhiback.service.IPictureService;
import com.youzhiback.utils.FtpUtil;
import com.youzhiback.utils.IDUtils; /**
* 图片上传服务
* <p>Title: PictureServiceImpl</p>
* <p>Description: </p>
* @version 1.0
*/
@Service
public class PictureServiceImpl implements IPictureService { @Value("${FTP_ADDRESS}")
private String FTP_ADDRESS;
@Value("${FTP_PORT}")
private Integer FTP_PORT;
@Value("${FTP_USERNAME}")
private String FTP_USERNAME;
@Value("${FTP_PASSWORD}")
private String FTP_PASSWORD;
@Value("${FTP_BASE_PATH}")
private String FTP_BASE_PATH;
@Value("${IMAGE_BASE_URL}")
private String IMAGE_BASE_URL; @Override
public Map uploadPicture(MultipartFile uploadFile) {
Map resultMap = new HashMap();
try {
//生成一个新的文件名
//取原始文件名
String oldName = uploadFile.getOriginalFilename();
//生成新文件名
//UUID.randomUUID();
String newName = IDUtils.genImageName();
newName = newName + oldName.substring(oldName.lastIndexOf("."));
//图片上传
String imagePath = new DateTime().toString("/yyyy/MM/dd");
boolean result = FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD,
FTP_BASE_PATH, imagePath, newName, uploadFile.getInputStream());
//返回结果
if(!result) {
resultMap.put("error", 1);
resultMap.put("message", "文件上传失败");
return resultMap;
}
resultMap.put("error", 0);
resultMap.put("url", IMAGE_BASE_URL + imagePath + "/" + newName);
return resultMap; } catch (Exception e) {
resultMap.put("error", 1);
resultMap.put("message", "文件上传发生异常");
return resultMap;
}
} }
这样就好了完成了一整套的上传