SpringMVC+kindEditor批量上传图片详细解析

来源:互联网 发布:淘宝发货时间有限制吗 编辑:程序博客网 时间:2024/06/07 01:45

首先去官网下载jar包:http://kindeditor.net/down.php

将jar包解压放到项目中

在jsp界面中引入jar包中的js

<script charset="utf-8" src="<%=request.getContextPath() %>/resource/kindeditor-4.1.7/kindeditor-min.js"></script><script charset="utf-8" src="<%=request.getContextPath() %>/resource/kindeditor-4.1.7/lang/zh_CN.js"></script>

在jsp中加入

<textarea name="productHTML" id="productHTML"  data-rule="商品介绍;required;productHTML;"   style="width:100%;height:500px;visibility:hidden;" ><c:out value="${e.productHTML}" /></textarea>

在<script>中写事件

var editor;KindEditor.ready(function(K) {editor = K.create('textarea[name="productHTML"]', {uploadJson : '${ctx}/manage/upload/imageUpload.action',//服务器端的地址            allowImageUpload  : true//运行上传图片});});

后台,kindEditor的批量上传,是使用ajax一个图片一个图片的上传的,

注意返回的数据一定要是json类型的,否则图片不会插入到textarea中

@Controller@RequestMapping("/manage/upload")public class ImageUploadAction {@RequestMapping("/imageUpload")@ResponseBodypublic JSONObject save(HttpServletRequest request,HttpServletResponse response){HashMap<String, String> extMap = new HashMap<String, String>();//支持的文件类型extMap.put("image", "jpg,jpeg,png,bmp"); //最大文件大小          long maxSize = 32505856;                  //是否选择文件        if(!ServletFileUpload.isMultipartContent(request)){          return getError("请选择文件!");        }                  //获取文件类型        String dirName = request.getParameter("dir");        if (dirName == null) {        dirName = "image";        }                if(!ServletFileUpload.isMultipartContent(request)){        return getError("请选择文件!");        }                MultipartHttpServletRequest mrequest= (MultipartHttpServletRequest)request;        Map map=mrequest.getFileMap();        Collection<MultipartFile> c = map.values();        Iterator item = c.iterator();                //遍历选择的图片        JSONObject obj =null;        while (item.hasNext()) {        CommonsMultipartFile file=(CommonsMultipartFile) item.next();        FileItem fileItem=file.getFileItem();        long fileSize = file.getSize();    //检查文件大小    if(file.getSize() > maxSize){    return getError("上传文件大小超过限制。");    }    //检查扩展名    String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();    if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){    return getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");    }        //上传到服务器上去    Map<String,String> params = new HashMap<String, String>();    params.put("fsd", "sdf");    Map<String, String> headers = new HashMap<String, String>();    String s;try {s = HttpUtil.uploadimage(fileItem.getInputStream(),params,headers);//上传到远程服务器JSONObject resultJson = JSONObject.fromObject(s);    obj =new JSONObject();    if("1".equals(resultJson.getString("rs"))){    String[] urls=resultJson.getString("paths").split("\"");    obj.put("error", 0);    if(urls.length==3){    obj.put("url", urls[1]);    }    return obj;    }else{    return getError(resultJson.getString("msg"));    }    } catch (IOException e) {return getError("服务器异常!请稍后重试!");}        }        return getError("未知错误!请稍候");}private static JSONObject getError(String message){JSONObject obj =new JSONObject();obj.put("error", 1);obj.put("message", message);return obj;}}


public static String uploadimage(InputStream ins, Map<String, String> params, Map<String, String> headers) {OutputStream out = null;DataInputStream in = null;HttpURLConnection con = null;HttpURLConnection conn = null;try {URL urlObj = new URL(REMOTE_UPLOAD_PIC + "?" + sendParams(params));con = (HttpURLConnection) urlObj.openConnection();/** * 设置关键值 */con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式con.setDoInput(true);con.setDoOutput(true);con.setUseCaches(false); // post方式不能使用缓存// 设置请求头信息con.setRequestProperty("Connection", "Keep-Alive");con.setRequestProperty("Charset", "UTF-8");con.setConnectTimeout(15000);con.setReadTimeout(6000);// 设置边界String BOUNDARY = "----------" + System.currentTimeMillis();con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY);// 请求正文信息// 第一部分:StringBuilder sb = new StringBuilder();sb.append("--"); // ////////必须多两道线sb.append(BOUNDARY);sb.append("\r\n");sb.append("Content-Disposition: form-data;name=\"myFile\";filename=\"" + "abc.jpg" + "\"\r\n");/*String suffix = imageUrl.substring(imageUrl.lastIndexOf(".") + 1);String cType = ContentTypeEnum.valueOf(suffix.toUpperCase()).getCtype();*/sb.append("Content-Type:image/png\r\n\r\n");byte[] head = sb.toString().getBytes("utf-8");// 获得输出流out = new DataOutputStream(con.getOutputStream());out.write(head);/*URL readIn = new URL(imageUrl);conn = (HttpURLConnection) readIn.openConnection();for (Map.Entry<String, String> e : headers.entrySet()) {conn.addRequestProperty(e.getKey(), e.getValue());}conn.setConnectTimeout(15000);conn.setReadTimeout(6000);*/// 文件正文部分in = new DataInputStream(ins);int bytes = 0;byte[] bufferOut = new byte[1024];while ((bytes = in.read(bufferOut)) != -1) {out.write(bufferOut, 0, bytes);}// 结尾部分byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线out.write(foot);out.flush();/** * 读取服务器响应,必须读取,否则提交不成功 */if (con.getResponseCode()==200) {String saaUrl = readResponse(con);//log.info("HttpUtil.uploadimage success ["+imageUrl+","+params+"]");return saaUrl;} else {//log.info("HttpUtil.uploadimage failed ["+imageUrl+","+params+"]");return "{\"rs\":-1}";}} catch (FileNotFoundException e) {//log.error("HttpUtil.uploadimage["+imageUrl+","+params+"]", e);return "{\"rs\":2}";} catch (Exception e) {//log.error("HttpUtil.uploadimage["+imageUrl+","+params+"]", e);return "{\"rs\":1}";} finally{if(in!=null){try {in.close();} catch (IOException e) {e.printStackTrace();}}if(out!=null){try {out.close();} catch (IOException e) {e.printStackTrace();}}if(con!=null){con.disconnect();}if(conn!=null){conn.disconnect();}}}


1 0
原创粉丝点击