EasyUI、SpringMVC上传文件

效果

EasyUI、SpringMVC上传文件_第1张图片

由于传入的url是一个假的,所以回显的图片和保存的图片不一致

1.js

kingEditorParams : {
   filePostName  : "uploadFile",
   uploadJson : '/pic/upload',
   dir : "image"
},
// 初始化图片上传组件
initPicUpload : function(data){
   $(".picFileUpload").each(function(i,e){
      var _ele = $(e);
      _ele.siblings("div.pics").remove();
      _ele.after('
 
    '); // 回显图片 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("
  • "); } } } $(e).click(function(){ var form = $(this).parentsUntil("form").parent("form"); 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(".pics ul").append("
  • "); }); form.find("[name=image]").val(imgArray.join(",")); editor.hideDialog(); } }); }); }); }); }, /** * 初始化单图片上传组件
    * 选择器为:.onePicUpload
    * 上传完成后会设置input内容以及在input后面追加 */ 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(""); this.hideDialog(); } }); }); }); }

    2.jsp

    
        商品图片:
        
            上传图片
             
        
    

    3.后端实现

    3.1封装ImageVO
    特定的格式信息{“error”:0,“url”:“图片的保存路径”,“width”:图片的宽度,“height”:图片的高度}

    根据easyUI的格式信息封装ImageVO类

    package com.jt.vo;
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import lombok.experimental.Accessors;
    import java.io.Serializable;
    /**
     * @Author WL
     * @Date 2020-9-29 15:51
     * @Version 1.0
     * 上传图片的封装类
     */
    @Data
    @Accessors(chain = true)
    @NoArgsConstructor
    @AllArgsConstructor
    public class ImageVo implements Serializable {
    
        private Integer error;//   0正常
        private String url; // 图片访问的虚拟路径
        private Integer width;
        private Integer height;
        
        // 设定上传失败的方法
        public static ImageVo faile() {
            return new ImageVo(1, null, null, null);
        }
        public static ImageVo success(String url, Integer width, Integer height) {
            return new ImageVo(0, url, width, height);
        }
    }
    3.2控制层FileController
    /**
     *  http://localhost:8091/pic/upload?dir=image  ; image代表上传的是一张图片
     * @param uploadFile
     * @return 特定的格式信息{“error”:0,“url”:“图片的保存路径”,“width”:图片的宽度,“height”:图片的高度}
     */
    @RequestMapping("/pic/upload")
    public ImageVo file2(MultipartFile uploadFile) {
        return fileService.upload(uploadFile);
    }
    3.3 image.properties
    //  图片保存地址
    image.rootPat=D:/image/
    image.urlPat=http://image.jt.com
    3.4FileService;FileServiceImpl
    public interface FileService {
        ImageVo upload(MultipartFile uploadFile);
    }
    @Service
    @PropertySource("classpath:/properties/image.properties")   //容器动态的加载配置文件
    public class FileServiceImpl implements FileService {
    
        @Value("${image.urlPat}")
        private String urlPath; //值会发生变化
        @Value("${image.rootPat}")
        private String rootPath;
        private static Set img;
        static {
            img = new HashSet<>();
            img.add(".png");
            img.add(".jpg");
            img.add(".gif");
        }
        
     /**
     * 上传的文件要有完善的校验功能
     * 1.校验后缀是否为图片
     * 2.校验是否为恶意程序
     * 3.防止文件数量太多,分目录存储
     * 4.防止文件重名
     * 5.实现文件上传
     *
     * @param uploadFile
     * @return
     */
    @Override
    public ImageVo upload(MultipartFile uploadFile) {
      String imageName = uploadFile.getOriginalFilename();
            int index = imageName.lastIndexOf(".");
            String imageType = imageName.substring(index);
            if (!img.contains(imageType.toLowerCase())) {
                return ImageVo.faile();
            }
            // 校验是否为恶意程序
            BufferedImage read = null;
            try {
                read = ImageIO.read(uploadFile.getInputStream());
                int width = read.getWidth();
                int height = read.getHeight();
                if (width == 0 || height == 0) {
                    return ImageVo.faile();
                }
                //防止文件数量太多,分目录存储 yyyy/MM/dd 
                String fileCreated = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
                String filePath = rootPath + fileCreated;
                File file = new File(filePath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                // 防止重名UUID
                String UUID = java.util.UUID.randomUUID().toString().replace("-", "");
                String fileName = UUID + imageType;
                String realFilePath = filePath + fileName;
                File file1 = new File(realFilePath);
                // 上传
                uploadFile.transferTo(file1);
                //  目前此url是一个假的
                return ImageVo.success("http://img30.360buyimg.com/sku/jfs/t1/107693/18/18443/466040/5ec22793Eacc2d45c/f9431c7d8f3f0723.jpg", width, height);
            } catch (IOException e) {
                e.printStackTrace();
                return ImageVo.faile();
            }
        }
    }

    你可能感兴趣的:(spring-mvc,javascript,maven)