kindeditor通过action上传图片

本文介绍如何基于已有的代码进行改进,实现一个高效且安全的图片上传系统。通过设置文件大小限制、检查文件类型、确保目录权限,并利用通用工具进行文件复制,最终返回JSON响应,提供上传图片的URL。此过程涉及HTTP请求处理、文件操作和日志记录等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下是基本上借鉴别人的代码,只是稍微完善一下

UploadImgAction.java

import com.opensymphony.xwork2.ActionSupport;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.json.simple.JSONObject;

import yanwo.web.util.Utils;

/**
 *
 * @author pengmaokui
 */
public class UploadImgAction extends ActionSupport{
    private final long MAX_SIZE = 2*1024*1024;
    Log log = LogFactory.getLog(this.getClass());
    
    private File imgFile; //页面传过来的数据 以下都是
    private String imgFileFileName;
    private String imgWidth;
    private String imgHeight;
    private String align;
    private String imgTitle;

    public void setImgFile(File imgFile) {
        this.imgFile = imgFile;
    }

    public void setImgFileFileName(String imgFileFileName) {
        this.imgFileFileName = imgFileFileName;
    }

    public void setImgWidth(String imgWidth) {
        this.imgWidth = imgWidth;
    }

    public void setImgHeight(String imgHeight) {
        this.imgHeight = imgHeight;
    }

    public void setAlign(String align) {
        this.align = align;
    }

    public void setImgTitle(String imgTitle) {
        this.imgTitle = imgTitle;
    }
    
    public String uploadImg() {
        HttpServletRequest request = ServletActionContext.getRequest();  
          HttpServletResponse response = ServletActionContext.getResponse(); 
          
        response.setContentType("text/html; charset=UTF-8");
        // 文件保存目录路径
        String savePath = ServletActionContext.getServletContext().getRealPath("/") + "Content/news/";
        // 文件保存目录URL
        String saveUrl = request.getContextPath() + "/Content/news/";
        // 定义允许上传的文件扩展名
        String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };
        // 最大文件大小
        long maxSize = MAX_SIZE;
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e1) {
            log.error(e1);
        }

        if (imgFile == null) {
            out.println(getError("请选择文件。"));
            return null;
        }

        // 检查目录
        File uploadDir = new File(savePath);
        if (!uploadDir.isDirectory()) {
            out.println(getError("上传目录不存在。"));
            return null;
        }
        // 检查目录写权限
        if (!uploadDir.canWrite()) {
            out.println(getError("上传目录没有写权限。"));
            return null;
        }
        // 创建文件夹
        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();
        }
        String fileExt = imgFileFileName.substring(imgFileFileName.lastIndexOf(".") + 1).toLowerCase();
        if (!Arrays.<String> asList(fileTypes).contains(fileExt)) {
            out.println(getError("上传文件扩展名[" + fileExt + "]是不允许的扩展名。"));
            return null;
        }
        if (imgFile.length() > maxSize) {
            out.println(getError("[ " + imgFileFileName + " ]超过单个文件大小限制,文件大小[ " + imgFile.length() + " ],限制为[ " + maxSize + " ] "));
            return null;
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
        File uploadedFile = new File(savePath, newFileName);
        try {
            Utils.copy(imgFile, uploadedFile);
            JSONObject obj = new JSONObject();
            obj.put("error", 0);
            obj.put("url", saveUrl + newFileName);
            log.debug(obj);
            out.println(obj.toString());
            log.debug("上传图片:[" + uploadedFile.getName() + "]" + ">>>[" + newFileName + "]成功");
        } catch (Exception e) {
            log.error("图片上传失败:" + e);
        }
        return null;
    }
    private String getError(String message) {
        JSONObject obj = new JSONObject();
        obj.put("error", 1);
        obj.put("message", message);
        log.debug(obj);
        return obj.toString();
    }
}

copy(Filesrc,File dst);

public static void copy(File src, File dst) {
        try {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = new BufferedInputStream(new FileInputStream(src),BUFFER_SIZE);
                out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
                byte[] buffer = new byte[BUFFER_SIZE];
                while (in.read(buffer) > 0) {
                    out.write(buffer);
                }
            } finally {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

struts.xml

<action name="uploadImg" class="yanwo.web.manage.action.UploadImgAction" method="uploadImg">
    </action>

jsp

options = {
                uploadJson : './uploadImg.do',
                fileManagerJson : '../editor/jsp/file_manager_json.jsp',
                allowFileManager : true,
                 items : [
                    'source', '|', 'undo', 'redo', '|', 'preview', 'cut', 'copy', 'paste',
                    'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
                    'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
                    'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '|',
                    'formatblock', 'fontname', 'fontsize', '/', 'forecolor', 'hilitecolor', 'bold',
                    'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage',
                    'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
                    'link', 'unlink', '|', 'about']
            }
            KindEditor.ready(function(K) {
                    window.editor = K.create('#editor_id',options);
            });
        </script>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值