zoukankan      html  css  js  c++  java
  • struts中用kindeditor实现的图片上传并且显示在页面上

      做公司网站的时候由于需要在内容属性中加入图片,所以就有了这个问题,本来一开始找几篇文章看都是讲修改kindeditor/jsp/file_manager_json.jsp和upload_json.jsp,可我改了半天地址,还是没改对,所以想到另一个方法,因为upload_json.jsp的主要功能就是上传图片呗,用的是java语言,在jsp中代码都用<%%>包起来了,所以我直接页面中上传功能那里直接去找的action里面的方法,然后用java去写,内容是在网上找的一个写好的,不过介绍的不好,我这里在几个重点位置上讲一下,根据各位的项目不同,对应该一下就可以了。

      首先说一下我的kindeditor放在项目的webroot下,位置就是这样,

    然后就是在要放kindeditor文本编辑器的页面,name="content" 就是文本的name。

    里面abc!upload是我的abc!action的方法upload,里面是上传的代码,

    package action;


    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.PrintWriter;
    import java.text.SimpleDateFormat;
    import java.util.Arrays;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Random;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import org.apache.log4j.Logger;
    import org.apache.struts2.ServletActionContext;
    import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
    import org.json.JSONException;
    import org.json.JSONObject;

    import com.opensymphony.xwork2.ActionSupport;


    /**
    * kindeditor 图片上传类(单个图片上传)
    * @author lijinlong
    *
    */
    public class abcaction extends ActionSupport {
    private static final long serialVersionUID = -5324165857715375773L;
    private Logger log = Logger.getLogger(this.getClass());
    private String imgPath="C:/Program Files/Apache Software Foundation/Tomcat 7.0/webapps/foodweb/attached";//存储路径, 绝对路径
    // private String imgPath="F:/Users/03/AppData/Local/MyEclipse/作品/.metadata/.me_tcat/webapps/foodweb/attached";
    private String imgUrl="";//显示url, 相对路径
    private String ip;
    private String port;
    private String context;

    public String upload() throws FileUploadException, IOException, JSONException{
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    PrintWriter out = response.getWriter();

    String savePath = imgPath + "/";

    File test = new File(savePath);
    if(!test.exists()){
    test.mkdirs();
    }
    //文件保存目录URL
    String saveUrl = imgUrl + "/";

    //定义允许上传的文件扩展名
    HashMap<String, String> extMap = new HashMap<String, String>();
    extMap.put("image", "gif,jpg,jpeg,png,bmp");
    // extMap.put("flash", "swf,flv");
    // extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
    // extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

    //最大文件大小
    // long maxSize = 1000000;

    response.setContentType("text/html; charset=UTF-8");

    if(!ServletFileUpload.isMultipartContent(request)){
    out.print(getError("请选择文件。"));
    return "err";
    }
    //检查目录
    File uploadDir = new File(savePath);
    if(!uploadDir.isDirectory()){
    out.print(getError("上传目录不存在。"));
    return "err";
    }
    //检查目录写权限
    if(!uploadDir.canWrite()){
    out.print(getError("上传目录没有写权限。"));
    return "err";
    }

    String dirName = request.getParameter("dir");
    if (dirName == null) {
    dirName = "image";
    }
    if(!extMap.containsKey(dirName)){
    out.print(getError("目录名不正确。"));
    return "err";
    }
    //创建文件夹
    savePath += dirName + "/";
    saveUrl += dirName + "/";

    File saveDirFile = new File(savePath);
    if (!saveDirFile.exists()) {
    saveDirFile.mkdirs();
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String ymd = sdf.format(new Date());
    savePath += ymd + "/";
    saveUrl += ymd + "/";

    File dirFile = new File(savePath);
    if (!dirFile.exists()) {
    dirFile.mkdirs();
    }


    MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper)request;
    String fileName = wrapper.getFileNames("imgFile")[0];
    File file = wrapper.getFiles("imgFile")[0];

    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){
    out.print(getError("上传文件扩展名是不允许的扩展名。 只允许" + extMap.get(dirName) + "格式。"));

    }
    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
    String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;

    saveUrl += newFileName;

    FileOutputStream fos = new FileOutputStream(savePath + newFileName);
    byte[] buffer = new byte[1024];
    InputStream in = new FileInputStream(file);

    try {
    int num = 0;
    while ((num = in.read(buffer)) > 0) {
    fos.write(buffer, 0, num);
    }
    } catch (Exception e) {
    e.printStackTrace(System.err);
    } finally {
    try{
    if(in != null)
    in.close();
    if(fos != null)
    fos.close();
    }catch(IOException e){}
    }

    JSONObject obj = new JSONObject();
    obj.put("error", 0);
    obj.put("url", "http://"+this.getIp() + ":" + this.getPort()+saveUrl);
    obj.put("url", "http://www.foodweb.com.cn/attached/"+saveUrl);

    out.print(obj.toString());


    return null;
    }
    private String getError(String message) throws JSONException {
    JSONObject obj = new JSONObject();
    obj.put("error", 1);
    obj.put("message", message);
    return obj.toString();
    }


    public String getImgPath() {
    return imgPath;
    }
    public void setImgPath(String imgPath) {
    this.imgPath = imgPath;
    }

    public String getIp() {
    return ip;
    }

    public void setIp(String ip) {
    this.ip = ip;
    }

    public String getPort() {
    return port;
    }

    public void setPort(String port) {
    this.port = port;
    }

    public String getContext() {
    return context;
    }

    public void setContext(String context) {
    this.context = context;
    }
    public String getImgUrl() {
    return imgUrl;
    }
    public void setImgUrl(String imgUrl) {
    this.imgUrl = imgUrl;
    }
    }

    以下是几个重点要设置的方面:

    1.imgpath=""里面的内容是存储的路径,就是东西存到哪里,这是服务器的位置,在myeclipse就是Tomcat中的位置,foodweb是我的项目名字,attached是放在项目webroot下的文件,用来存储照片的,另外还有点注意,就是注意斜杠的方向,这个是/,而从电脑上复制的地址是,这个路径没什么提醒的了。

    2.imgurl=“”里面的内容是相对路径,我测试过,里面就空着就行,跟上面的代码一样不用管。

    3.代码的151行那块,有段这个  obj.put("url", "http://www.foodweb.com.cn/attached/"+saveUrl); 代码,这个前面不用改,改后面的值就好,http://www.foodweb.com.cn/attached/,这是服务器的地址,前面的www.foodweb.com.cn是网址,后面的attached是项目中webroot下的文件。

    然后大致就是这些了,如果各位有什么问题指出,可以评论,我每天上线可以看见,可以交流一下,最后注意斜杠什么的都别落下就好。

        

    转载于:https://www.cnblogs.com/xiechenboblog/p/7680980.html

  • 相关阅读:
    浅谈Linux文件操作
    数据结构学习--队列
    CODE[VS] 1099 字串变换
    CODE[VS] 1026 逃跑的拉尔夫
    CODE[VS] 3027 线段覆盖 2
    LeetCode8.字符串转换整数(atoi) JavaScript
    JS实现继承 JavaScript
    LeetCode7.整数反转 JavaScript
    LeetCode6.Z字形变换 JavaScript
    LeetCode5.最长回文子串 JavaScript
  • 原文地址:https://www.cnblogs.com/twodog/p/12139185.html
Copyright © 2011-2022 走看看