关于spring-mvc:EasyUISpringMVC上传文件

41次阅读

共计 4157 个字符,预计需要花费 11 分钟才能阅读完成。

成果

因为传入的 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('<div class="pics">
             <ul></ul>
          </div>');
 // 回显图片
 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("<li><a href='"+imgs[i]+"'target='_blank'><img src='"+imgs[i]+"'width='80'height='50'/></a></li>");
             }
          }
       }
       $(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("<li><a href='"+data.url+"'target='_blank'><img src='"+data.url+"'width='80'height='50'/></a></li>");
         });
         form.find("[name=image]").val(imgArray.join(","));
         editor.hideDialog();}
   });
          });
       });
   });
},
  /**
 * 初始化单图片上传组件 <br/> * 选择器为:.onePicUpload <br/>
 * 上传实现后会设置 input 内容以及在 input 前面追加 <img> 
   */
 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("<a href='"+url+"'target='_blank'><img src='"+url+"'width='80'height='50'/></a>");
            this.hideDialog();}
      });
   });
});
  }

2.jsp

<tr>
    <td> 商品图片:</td>
    <td>
        <a href="javascript:void(0)" class="easyui-linkbutton picFileUpload"> 上传图片 </a>
         <input type="hidden" name="image"/>
    </td>
</tr>

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.3FileService;FileServiceImpl
public interface FileService {ImageVo upload(MultipartFile uploadFile);
}
@Service
public class FileServiceImpl implements FileService {
    private static String rootPath = "D:/image/";
    private static Set<String> 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();}
    }
}

正文完
 0