You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Summernote文本框无法获取图片名称,仅能上传文件问题求助

解决Summernote插入图片时无法获取原图片名称的问题

问题分析

当前代码可完成图片上传至指定目录,但插入到Summernote的图片未携带原图片名称信息——核心原因是后端仅返回文件路径,前端调用insertImage方法时也只传入URL,未传递原文件名作为图片的替代文本(alt属性)。

解决方案

1. 修改后端PHP代码(contentupload.php)

将返回格式改为JSON,同时返回文件路径和原文件名:

<?php 
if(empty($_FILES['file']))
{
    exit(json_encode(['error' => '未上传文件'])); 
}
$originalFileName = $_FILES["file"]["name"];
$temp = explode(".", $originalFileName);
$newfilename = round(microtime(true)) . '.' . end($temp);
$destinationFilePath = './img-uploads/'.$newfilename ;
if(!move_uploaded_file($_FILES['file']['tmp_name'], $destinationFilePath)){
    echo json_encode(['error' => '文件上传失败']);
}
else{
    echo json_encode([
        'url' => $destinationFilePath,
        'originalName' => $originalFileName
    ]);
}
?>

2. 修改前端JS代码

在AJAX回调中解析JSON数据,插入图片时传入原文件名作为alt属性:

function uploadFile(file) {
    data = new FormData();
    data.append("file", file);

    $.ajax({
        data: data,
        type: "POST",
        url: "contentupload.php", // 替换为你的实际接口地址
        cache: false,
        contentType: false,
        processData: false,
        dataType: 'json', // 指定响应为JSON格式
        success: function(response) {
            if (response.error) {
                console.error(response.error);
                return;
            }
            // 插入图片时携带原文件名作为alt属性
            $('#summernote').summernote("insertImage", response.url, response.originalName);
            console.log('图片上传完成:', response.url, '原文件名:', response.originalName);
        },
        error: function(xhr, status, error) {
            console.error('上传出错:', error);
        }
    });
}

效果说明

修改后,Summernote中插入的图片会自动带上原图片名称作为alt属性,既解决了“无法获取图片名称”的问题,也增强了图片的可访问性。同时新增的错误处理逻辑,能更方便排查上传过程中出现的问题。

内容的提问来源于stack exchange,提问作者nickelaj xxx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 22:35:19