【问题标题】:AJAX post form with file upload带有文件上传的 AJAX 发布表单
【发布时间】:2020-04-27 05:25:01
【问题描述】:

我有这个我似乎无法解决的问题,这肯定是一个菜鸟的事情,但在这里,我正在尝试过去的值并使用相同的表单上传文件,但文件没有传递给 php 函数.

我的 ajax html:

<form name="create_batch" method="post" role="form">
   <input type="hidden" name="token" value="<?= \Middlewares\Csrf::get() ?>" required="required" />
   <input type="hidden" name="request_type" value="create" />
   <input type="hidden" name="project_id" value="<?= $data->project->project_id ?>" />
   <input type="hidden" name="type" value="batch" />

   <div class="notification-container"></div>

   <div class="form-group">
      <label><i class="fa fa-fw fa-signature fa-sm mr-1"></i> <?= $this->language->create_link_modal->input->location_url ?></label>
   <input type="text" class="form-control" name="location_url" required="required" placeholder="<?= $this->language->create_link_modal->input->location_url_placeholder ?>" />
   </div>
   <div class="form-group">
     <input type="file" name="file">
   </div>
   <div class="form-group">
      <label><i class="fa fa-fw fa-link"></i> <?= $this->language->create_link_modal->input->url ?> 
      </label>
      <input type="text" class="form-control" name="url" placeholder="<?= $this->language->create_link_modal->input->url_placeholder ?>" />
   </div>
   <div class="text-center mt-4">
      <button type="submit" name="submit" class="btn btn-primary"><?= $this->language->create_link_modal->input->submit ?></button>
   </div>
</form>
<script>
    $('form[name="create_batch"]').on('submit', event => {

        $.ajax({
            type: 'POST',
            url: 'link-ajax',
            data: $(event.currentTarget).serialize(),
            success: (data) => {
                if(data.status == 'error') {

                    let notification_container = $(event.currentTarget).find('.notification-container');

                    notification_container.html('');

                    display_notifications(data.message, 'error', notification_container);

                }

                else if(data.status == 'success') {

                    /* Fade out refresh */
                    fade_out_redirect({ url: data.details.url, full: true });

                }
            },
            dataType: 'json'
        });

        event.preventDefault();
    })
</script>

这会将数据发布到 php 文件和相应的函数中,但只有字段通过。该文件(即 csv)未通过。当然我的 ajax 脚本有问题,它只允许通过 post 传递表单的值,而不是文件。

我的 php 是这样的:

<?php

if(!empty($_FILES)){

$fh = fopen($_FILES['file']['tmp_name'], 'r+');
$i=0;
$lines = array();

while( ($row = fgetcsv($fh, 8192)) !== FALSE ) {
    $lines[] = $row;

$location_url = $lines[$i][0];
$url = $lines[$i][1];
$umt_source = $lines[$i][2];
$utm_medium = $lines[$i][3];
$utm_campaign = $lines[$i][4];
$utm_term = $lines[$i][5];
$utm_content = $lines[$i][6];

$i=$i+1;

}
fclose($fh);
}

$_POST['project_id'] = (int) $_POST['project_id'];
$_POST['location_url'] = trim(Database::clean_string($_POST['location_url']));
$_POST['url'] = !empty($_POST['url']) ? get_slug(Database::clean_string($_POST['url'])) : false;
...........

有什么帮助吗?非常感谢。

【问题讨论】:

    标签: php html jquery ajax forms


    【解决方案1】:

    为了发送多部分表单数据,您需要创建并发送一个表单数据对象。

    见下面的例子 -

                     var formdata = new FormData($('#formId')[0]);
                        $.ajax({
                            url: URL,
                            type: 'POST',
                            dataType: 'json',
                            async: false,
                            cache: false,
                            contentType: false,
                            processData: false,
                            data: formdata,
                            success: function (response) {
                                $('#responseMsg').html(response.msg);
                            }
                        });
    

    在服务器端,您可以通过$_POST 获取您的数据,通过$_FILES 获取文件

    【讨论】:

      【解决方案2】:

      解决方案。

          $("form#create_batch").submit(function(e) {
          e.preventDefault();
          var formData = new FormData(this);
      
          $.ajax({
              url: 'link-ajax',
              type: 'POST',
              data: formData,
              dataType: 'json',
              success: (data) => {
                      if(data.status == 'error') {
      
                          let notification_container = $(event.currentTarget).find('.notification-container');
      
                          notification_container.html('');
      
                          display_notifications(data.message, 'error', notification_container);
      
                      }
      
                      else if(data.status == 'success') {
      
                          /* Fade out refresh */
                          fade_out_redirect({ url: data.details.url, full: true });
      
                      }
                  },
              cache: false,
              contentType: false,
              processData: false
          });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-12
        • 1970-01-01
        • 2011-02-26
        • 2013-10-25
        • 2012-06-13
        • 2012-09-20
        • 2017-06-08
        • 2013-06-05
        相关资源
        最近更新 更多