xheditor上传图片的java实现
最近一个项目中因为框架的原因,很多文本编辑器都不兼容,最后找到xheditor,这个富文本编辑器的确不错,功能基本都能满足,只是上传图片的java接口需要自己写,因此,测试了两种方法,最终成功。分享给大家。
xheditor官方给出了上传接口。因此我们只需要调用自己的Action按照它指定的json格式返回一个json数据就可以了。
一、使用servlet时的实现方式,servlet的实现方式需要引入commons-fileupload-1.3.1.jar包。主要是用来解析前台传过来的请求。
1、前台页面的写法,当然要引入xheditor啦,这里我就写了。这里主要是upImgUrl要写上你后台的Servlet。
<textarea class="editor" name="articleContent" rows="35" cols="100" style="z-index:99;" upImgUrl="UploadFileServlet" upImgExt="jpg,jpeg,gif,png" > ${article.articlecontent } </textarea>
2、后台servlet的写法。配置文件中我也省略了,这里仅仅是一个Servlet。需要注意的,这里要引入commons-fileupload-1.3.1.jar包来解析请求。
package com.zk.web.action; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class UploadFileServlet extends HttpServlet { private static final long serialVersionUID = 1L; private ServletContext sc; public void init(ServletConfig config) { sc = config.getServletContext(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletOutputStream out = response.getOutputStream(); request.setCharacterEncoding( "utf-8" ); response.setHeader("Content-Type" , "text/html"); String returnPath = ""; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); System.out.println("上传文件的大小:" + item.getSize()); System.out.println("上传文件的类型:" + item.getContentType()); System.out.println("上传文件的名称:" + item.getName()); returnPath = "images/"+item.getName(); //这里是取得项目地址 File forder = new File(sc.getRealPath("/")+"images/");
//判断文件夹是否存在 if (!forder.exists()) { forder.mkdir(); } File file = new File(sc.getRealPath("/")+"images/"+item.getName()); item.write(file); System.out.println("上传文件成功!"); } } catch (Exception e) { e.printStackTrace(); System.out.println("上传文件失败"); } //这里是关键,返回上传图片存储在服务器的地址。路径根据自己项目的路径调整。 out.print("{‘err‘:‘‘,‘msg‘:‘"+ returnPath.replace("\\", "/")+"‘}"); } }
二、使用spring mvc时的实现方式。uploadImage就是一个Action,
1、前台页面的写法,当然要引入xheditor啦,这里我就写了。这里主要是upImgUrl要写上你后台的Action。
<textarea class="editor" name="articleContent" rows="35" cols="100" style="z-index:99;"
upImgUrl="uploadImage.do" upImgExt="jpg,jpeg,gif,png" >
${article.articlecontent }
</textarea>
2、后台Action的写法,这里是使用的是sping mvc框架,spring没测试过,有需要的可以试试。
/** * 文本编辑器上传图片 * @param request * @param response * @return * @throws Exception */ public void uploadImage(HttpServletRequest request, HttpServletResponse response)throws Exception{ ServletOutputStream out = response.getOutputStream(); request.setCharacterEncoding( "utf-8" ); response.setHeader("Content-Type" , "text/html"); CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); // 设置编码 commonsMultipartResolver.setDefaultEncoding("utf-8"); if (commonsMultipartResolver.isMultipart(request)) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile image = multipartRequest.getFile("filedata"); String url = "images"+File.separator+Tool.dateToString(new Date(), "yyyyMMdd")+File.separator;
//这里可以从项目中取得你项目根目录的地址 String filePath = "D:/"+url; Random r = new Random(); if(image != null && !image.isEmpty()){ InputStream xtins = image.getInputStream(); String hj = new String(image.getOriginalFilename().getBytes("ISO-8859-1"),"UTF-8"); hj = hj.split("\\.")[1];
//这里用来生成文件名 String fileName = Tool.dateToString(new Date(), "yyyyMMddHHmmss")+r.nextInt(1000)+"."+hj; saveInputStreamToFile(filePath, fileName, xtins);
//这里是用来返回给xheditor的 out.print("{‘err‘:‘‘,‘msg‘:‘"+ (url+fileName).replace("\\", "/")+"‘}"); } } } /** * 保存文件流到指定路径 * @param filePath * @param fileName * @param inputStream * @throws Exception */ public void saveInputStreamToFile(String filePath, String fileName, InputStream inputStream) throws Exception { OutputStream os = null; try { File forder = new File(filePath); if (!forder.exists()) { forder.mkdir(); } File file = new File(filePath + fileName); os = new FileOutputStream(file); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); inputStream.close(); } catch (Exception ex) { ex.printStackTrace(); throw ex; } finally { if (inputStream != null) { inputStream.close(); } if (os != null) { os.close(); } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。