ueditor的集成

首先考虑的是图片的上传,js请求上传的回调方法里,需要服务器返回的结果里有url和state两个参数

这里有一句代码,把字符串转成json,我平日里都是用eval方法,这次是学到了。

json = (new Function("return " + result))();

后台处理的方法,根据js处理的要求,需要返回的数据结构就定下来了

@POST
    @Path("/ueditorupload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces("application/json; charset=utf-8")
    public String ueditorUploadFile(MultipartFormDataInput input) throws IOException {
        Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
        List<InputPart> inputParts = uploadForm.get("upfile");
        
//        String channel2xml = getStringValue(uploadForm, "upfile");
        
        if (inputParts == null) {
            return "{}";
        }
        
        String fileName = "";
        StringBuilder json = new StringBuilder();
        json.append("{");
        
        for (InputPart inputPart : inputParts) {
            try {
                MultivaluedMap<String, String> header = inputPart.getHeaders();
                fileName = getFileName(header);
                if (StringUtil.isEmpty(fileName)) {
                    //fileName = "blob.png";
                    continue;
                }
                
                String uploadPath = imageUploadPath(fileName);
                String uploadFullName = imagePathUtilAction.getImageBasePath() + uploadPath;
                
                InputStream inputStream = inputPart.getBody(InputStream.class, null);
                byte[] bytes = IOUtils.toByteArray(inputStream);
                
                if (FileUtil.writeFile(bytes, uploadFullName)) {
                    json.append("\"state\":\"SUCCESS\"");
                    json.append(",");
                    json.append("\"url\":\"" + imageUrlUtilAction.getImageBaseUrl() + uploadPath + "\"");
                } else {
                    json.append("\"state\":\"保存文件失败!\"");
                }
                
//                break;
                
            } catch (IOException e) {
                json.append("\"state\":\"异常!\"");
            }
        }
        
        json.append("}");
        return json.toString();
    }
    private String imageUploadPath(String fileName) {
        String day = DateUtil.format(new Date(), "yyyy/MM/dd");
        String fileExt = FileUtil.getFileExtName(fileName);

        return "/ueditor/" + day + "/" + EncryptUtil.encryptString(fileName) + "." + fileExt;
    }
    private String getFileName(MultivaluedMap<String, String> header) {
        String[] contentDisposition = header.getFirst("Content-Disposition").split(";");

        for (String filename : contentDisposition) {
            if ((filename.trim().startsWith("filename"))) {
                String[] name = filename.split("=");
                String finalFileName = name[1].trim().replaceAll("\"", "").replaceAll("/", "");
                return finalFileName;
            }
        }

        return "";
    }

 

posted @ 2020-10-23 14:52  1156740846  阅读(138)  评论(0编辑  收藏  举报