首页 > 解决方案 > 将 ajaxform 与 ajax 合并以上传图片

问题描述

我尝试在我的 nodejs 站点中创建上传照片。我使用此代码选择文件并上传图像:

 var fileData = null;

        function loadFile() {
            var preview = document.querySelector('file');
            var file    = document.querySelector('input[type=file]').files[0];
            var reader  = new FileReader();

            reader.onloadend = function () {
                fileData = file;
            }
            if (file) {
                reader.readAsDataURL(file);
            }
        }

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

            $.ajax({
              url: "/post_pdf/",
              type: "POST",
              data: data,
              enctype: 'multipart/form-data',
              processData: false,
              contentType: false,
              success: function(data) {
                  document.getElementById("result").innerHTML = 'Result: Upload successful';
              },
              error: function(e) {
                  document.getElementById("result").innerHTML = 'Result: Error occurred: ' + e.message;
              }
            });
        }

使用 loadfile 函数我选择我的图像,并使用 Uploadfile 函数我用 ajax 上传图像。如果我单独使用它,它的工作完美,并将图像上传到该位置。但是当我尝试将此代码添加到我的代码中时,它会产生很多错误。在我的代码中,我将 pug 文件中的所有表单发送到后端:

$('#account-form').ajaxForm({
    error : function(e){
        if (e.responseText == 'title-empty'){
            av.showInvalidTitle();
        }
    },
    success : function(responseText, status, xhr, $form){
        if (status == 'success')
        {
            $('.modal-alert').modal('show');
            console.log(responseText)
        }}
});

我尝试将 ajaxform 与 ajax 合并,但是当我合并 formdata 或我发送 ajaxform 时,文件的数据是发送错误。我如何合并代码?谢谢你的帮助。

标签: ajax

解决方案


尝试提交表单,它将使用您的图像提交表单。

  let form = $("#form_id");
            $.ajax({
                url : $(form).attr("action"),
                type: "POST",
                dataType: "json",
                processData: false,
                contentType: false,
                cache: false,
                data: new FormData(form[0]),
                success:function(data){

                },
                error: function (xhr, status, e) {

                }
            });

推荐阅读