Trumbowyg:Django 服务器可以检测文件上传但不能检测图像 URL 输入

Trumbowyg: Django server can detect file upload but not image URL input

我正在使用 Trumbowyg, a WYSIWYG JavaScript editor which has a feature of rendering images from URLs pasted in. It also has an upload plugin,它支持上传本地图像和自定义服务器端处理。

我的 python/django 函数 upload_image() 可以成功检测到上传的图像 - 但是当我使用 URL 图像输入时,我的 python 函数无法检测到它。 Trumbowyg 只是渲染图像而不通过我的 python 后端。

这是我的代码:

$('#id_content').trumbowyg({
    btnsDef: {
        // Create a new dropdown
        image: {
            dropdown: ['insertImage', 'upload'],
            ico: 'insertImage'
        }
    },
    // Redefine the button pane
    btns: [
        ['strong', 'em', 'del'],
        ['link'],
        ['image'], // Our fresh created dropdown
    ],
    plugins: {
        // Add imagur parameters to upload plugin for demo purposes
        upload: {
            serverPath: '/upload_image/',
            fileFieldName: 'content_image',
            urlPropertyName: 'url'
        }
    }
});
def upload_image(request):
    print('Success') #only prints when I use the upload input, not the URL input

为什么能检测到上传的图片,但检测不到URL输入?

如前所述,如果用户使用 URL 上传图像,Trumbowyg 不会将 URL 发送到后端。

但如果您真的想在自己的服务器上托管图像,有一种方法可以做到。

当用户提交表单时,您将在后端收到文本区域的内容。然后您可以阅读内容并查找 <img src="..."> 标签。

此时,您可以检查 src 值是否不以您的 S3 存储桶主机名开头,您可以使用 urllib or requests 库下载该图像,将其保存到您的存储桶并替换src 值。

由于提交的数据将采用 HTML 格式,请查看优秀的 Beautiful Soup。这将使解析 HTML 变得容易。