Drupal 7 文件上传(无hook_form)

Drupal 7 file upload (without hook_form)

本文关键字:hook form 文件 Drupal      更新时间:2023-09-26

这是一个让我在过去几天里难倒的难题。我在Drupal 7中使用模态表单,因此在hook_form系统之外工作,尝试上传图像。表单是通过 ajax 帖子提交的,这使我无法将文件与帖子一起提交。 我所做的是在 ajax 回调中,使用文件输入创建一个新的表单元素,然后触发提交,发布到我的模块定义的页面。

原始输入元素:

<input type="file" id="chooseImage" name"someImage" class="form-file">

JS触发提交:

$.ajax({
type:'POST',
url:$('#originalForm').attr('action'),
data: data,
success: function(response) {
    if (response.success) {
        $('<form id="imageForm" method="POST" action="upload/image/'+response.data.nid+'"></form>').appendTo($('#imageSubmit'));
        $('#chooseImage').appendTo($('#imageForm')); 
        console.log($('#imageForm'));
        $('#imageForm').submit(function(e){
            console.log(e);
            alert('freeze! hammertime...');
        });
        //This should post the file but it isn't...
        $('#imageForm').trigger('submit');
    }
},
dataType:'json'
});

提交事件可以很好地显示文件属性。但是,在后端,我的页面回调结束的地方...

    function myModule_image_upload($param){
        error_log('number of files = '.sizeof($_FILES));
    }

我没有显示任何发布的文件。我猜浏览器在 .submit() 运行后正在删除帖子中的文件数据,如果是这种情况,我可能对此无能为力,所以我必须在钩子系统中实现一个单独的菜单用于图像上传。

此外,无论这到底在做什么,它似乎都会永久破坏看门狗,迫使我重新导入一个新的转储。

试试这个:

$('<form id="imageForm" enctype="multipart/form-data" method="POST" action="upload/image/'+response.data.nid+'"></form>').appendTo($('#imageSubmit'));

所以你忘了设置编码类型。

另一个错误:

<input type="file" id="chooseImage" name"someImage" class="form-file">

应该是

<input type="file" id="chooseImage" name="someImage" class="form-file"/>