在TinyMCE 4图像上传中使用数据URI而不是blob

时间:2018-03-09 15:59:57

标签: javascript base64 blob image-uploading tinymce-4

使用TinyMCE 4,我正在尝试使用基本的本地文件选择器,例如their example中使用的文件选择器。

运行他们的示例后,我注意到生成的图像源是一个与base64相对的blob。

所以我的问题:是否可以使用base64而不是blob?

我认为file_picker_callback回调的第一个参数将被用作图像的源,所以我使用this answer调整了代码,我将数据URI作为第一个参数传递。

file_picker_types: 'image', 
// and here's our custom image picker
file_picker_callback: function (cb, value, meta) {
    var input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('accept', 'image/*');

    // Note: In modern browsers input[type="file"] is functional without 
    // even adding it to the DOM, but that might not be the case in some older
    // or quirky browsers like IE, so you might want to add it to the DOM
    // just in case, and visually hide it. And do not forget do remove it
    // once you do not need it anymore.

    input.onchange = function() {
        var file = this.files[0];
        var reader = new FileReader();

        reader.onload = function () {

            // Note: Now we need to register the blob in TinyMCEs image blob
            // registry. In the next release this part hopefully won't be
            // necessary, as we are looking to handle it internally.
            //var id = 'blobid' + (new Date()).getTime();
            //var blobCache =  tinymce.activeEditor.editorUpload.blobCache;
            //var base64 = reader.result.split(',')[1];
            //var blobInfo = blobCache.create(id, file, base64);

            //blobCache.add( blobInfo );

            // call the callback and populate the Title field with the file name

            cb(reader.result, { title: 'hola' });
        };
        reader.readAsDataURL( file );
    };

    input.click();
}

然而它不起作用,而是将源转换为blob,例如

<img src="blob:null/c8e90adb-4074-45b8-89f4-3f28c66591bb" alt="" /> 

如果我传递正常的字符串,例如test.jpg,它会生成

<img src="test.jpg" alt="" />

2 个答案:

答案 0 :(得分:0)

您看到的blob:格式实际上是Base64编码的二进制图像。如果您要将TinyMCE的内容发布到服务器,您确实会获得Base64数据。

您可以强制TinyMCE立即将该图像发送到您的服务器,按照以下步骤转换为“常规”图像:

https://www.tinymce.com/docs/advanced/handle-async-image-uploads/

答案 1 :(得分:0)

将以下代码添加到tinymce \ plugins \ quickbars \ plugin.js中,如图所示。

$.ajax({
            url: 'saveupload', // Upload Script
            enctype : 'multipart/form-data',
            type: 'post',
            data: {"imageString":base64,"imageType":blob.type,"imageName": blob.name},
            success: function(responseText) {
                var myJSON = JSON.parse(responseText);
                editor.insertContent(editor.dom.createHTML('img', { src: myJSON }));
            },
            error : function(xhr, ajaxOptions, thrownError) {
            }
          });

enter image description here

注意:如果您使用压缩版本,则可以使用任何压缩工具(例如yuicompressor)将其转换为压缩版本 我正在将图像上传到apache

servlet代码在下面

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    tbaService = new TBAServiceImpl();
    File f = new File("path");
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    Map<String, String[]> parameterNames = request.getParameterMap();
    Gson gson = new Gson();
    HttpSession session = request.getSession(true);

    long timeinMill = new Date().getTime();
    String uniqueFileName = "local_"+timeinMill+"_"+parameterNames.get("imageName")[0].replace(" ", "_");
    String fileType = parameterNames.get("imageType")[0].split("/")[1];
    try {

        BufferedImage image = null;
        byte[] imageByte;

        BASE64Decoder decoder = new BASE64Decoder();
        imageByte = decoder.decodeBuffer(parameterNames.get("imageString")[0]);
        ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
        image = ImageIO.read(bis);
        bis.close();

        // write the image to a file
        File outputfile = new File(filePath+uniqueFileName); //filePath = C:/Apache/htdocs/tba/images/
        ImageIO.write(image, fileType, outputfile);

        out.print(gson.toJson(uploadUrl+uniqueFileName)); //uploadUrl=http://localhost/test/images/
        out.flush();
        out.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}