使用显示错误的formdata上传文件:Uncaught ReferenceError:未定义fileInputElement

时间:2018-09-25 10:01:12

标签: javascript ajax form-data

我正在尝试使用FormData创建文件上传脚本,但出现错误:

Uncaught ReferenceError: fileInputElement is not defined

这是我目前的代码:

$("body").on("click","#addemployeebtn",function(){
    event.preventDefault();

    var formdata = new FormData();

    var file1 = formdata.append("copy_driverslicense", fileInputElement.files[0]);

    var $form = $("#employeeformadd");

    var $serialized = $form.serialize();

    var url = 'includes/addemployee.php';

    var posting = $.post(url, {
      serialized: $serialized,
      file1: $file
    });
    // Post to addemployee.php and get result message in .addemployee
    posting.done(function( data ) {
     $( ".addedemployee" ).empty().slideDown('fast').append( data );
    });
});

相关HTML:

<form id="employeeformadd" method="post" enctype="multipart/form-data">
    <input id="copy_driverslicense" type="file" class="filestyle" data-input="false" data-buttonname="btn-secondary">
</form>

我在做什么错了?

我正在使用此网站尝试学习如何执行此操作:https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

2 个答案:

答案 0 :(得分:0)

我不会考虑代码中的任何其他错误。正是引起错误“ UncaughtReference”的原因。参考上面给出的代码片段,变量'fileInputElement'没有定义任何导致错误的地方,因为它为null。并没有发现任何异常。

您应该考虑使用ID“ copy_driverslicence”访问InputElement,如下所述:

$("body").on("click","#addemployeebtn",function(){
    event.preventDefault();

    var formdata = new FormData();
//declare first the element;
 

   var fileInputElement=document.getElementById("copy_driverslicence");
    var file1 = formdata.append("copy_driverslicense",fileInputElement.files[0]);

    var $form = $("#employeeformadd");

    var $serialized = $form.serialize();

    var url = 'includes/addemployee.php';

    var posting = $.post(url, {
      serialized: $serialized,
      file1: $file
    });
    // Post to addemployee.php and get result message in .addemployee
    posting.done(function( data ) {
     $( ".addedemployee" ).empty().slideDown('fast').append( data );
    });
});

答案 1 :(得分:0)

HTML

 <input id="uploadImage" type="file" accept="" class="form-control" name="images" />

JavaScript

var formData = new FormData();
                        formData.append('file', $('#uploadImage')[0].files[0]);
                        //formData.append('category_name', category_name);
                        //formData.append('Language_ID', Language_ID);

                        $.ajax({
                         url:$('body').attr('url') + 'admin/media/add_image_category_data',
                         type:"post",
                         data: formData, //this is formData
                         processData:false,
                         contentType:false,
                         cache:false,
                         async:false,
                          success: function(data){