如果想要出现上传按钮,在xhEditor设置以下参数:
html5Upload : false //此属性必须为false
upImgUrl : "ImgUpload.action" //上传服务器接口
onUpload : insertUpload //服务器返回信息,JSON格式
一、前台代码
$(function() {
$('#content').xheditor( {
tools : 'full', //也可自定义tools,这里为full
html5Upload : false, //此属性必须为false 否则无法上传图片
upImgUrl : "ImgUpload.action",
onUpload : uploadImg
});
function uploadImg(data) {
//...回调函数
}
})
二、Struts2上传代码
public class ImgUploadAction extends ActionSupport {
private String err = "";
private String msg; //返回信息
private File filedata; //上传文件
private String filedataFileName; //文件名
public String imgUpload() {
//获取response、request对象
ActionContext ac = ActionContext.getContext();
HttpServletResponse response = (HttpServletResponse) ac.get(ServletActionContext.HTTP_RESPONSE);
HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);
response.setContentType("text/html;charset=gbk");
PrintWriter out = null;
try {
out = response.getWriter();
} catch (IOException e1) {
e1.printStackTrace();
}
String saveRealFilePath = ServletActionContext.getServletContext().getRealPath("/upload");
File fileDir = new File(saveRealFilePath);
if (!fileDir.exists()) { //如果不存在 则创建
fileDir.mkdirs();
}
File savefile;
savefile = new File(saveRealFilePath + "/" + filedataFileName);
try {
FileUtils.copyFile(filedata, savefile);
} catch (IOException e) {
err = "错误"+e.getMessage();
e.printStackTrace();
}
String fileName = request.getContextPath() + "/upload/" + filedataFileName;
msg = "{"err":"" + err + "","msg":"" + fileName + ""}";
out.print(msg); //返回msg信息
return null;
}
public String getErr() {
return err;
}
public void setErr(String err) {
this.err = err;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public File getFiledata() {
return filedata;
}
public void setFiledata(File filedata) {
this.filedata = filedata;
}
public String getFiledataFileName() {
return filedataFileName;
}
public void setFiledataFileName(String filedataFileName) {
this.filedataFileName = filedataFileName;
}
}三、Struts2配置文件
class="com.itmyhome.ImgUploadAction">
效果如图: