使用Ajax和Jquery上传文件 [英] Upload files with Ajax and Jquery

查看:65
本文介绍了使用Ajax和Jquery上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图弄清楚过去几个小时如何通过ajax上传文件而没有任何内容。

I've been trying to figure out how to upload a file through ajax for the past several hours and nothing.

以下是代码:
HTML :

Here's the code: HTML:

<form action="" method="post" id="uploadForm" enctype="multipart/form-data">

  <input type="file" name="image" id="image">
  <input type="submit">

</form>

JS:

<script>

jQuery(document).ready(function(){  
  jQuery('form#uploadForm').on('submit', function(e){
    e.preventDefault();

    var file = jQuery('#image')[0].files[0];
    var form_data = new FormData( jQuery("form#uploadForm")[0] );
    form_data.append( 'image', file );

    jQuery.ajax({
      url: 'index.php?a=do',
      type: 'POST',
      processData: false,
      contentType: false,
      cache: false,
      data: form_data,
      success: function(response) {
        console.log(response);
      },
    });

    return false;

  });
});

</script>

PHP:

<?php 
$a = isset($_GET['a']) ? $_GET['a'] : '';
if($a <> '') {
  echo "result - ";
  var_dump($_POST);
  die();
}
?>

结果我得到一个空数组,但如果我把文件字段留空,那么我得到:

As a result I get an empty array, however if I leave the file field empty, then I get:

result - array(1) {
  ["image"]=>
  string(9) "undefined"
}

我试过序列化(),serializeObject(),serializeArray(),$ .param和每个该死的时间我在控制台中得到未定义的函数错误。

I've tried serialize(), serializeObject(), serializeArray(), $.param and every damn time I get "undefined function" error in console.

我经历了几十个类似的问题在stackoverflow上没有任何帮助。我尝试使用$ .post而不是$ .ajax,包含form_data的data字段为空。

I went through dozens of similar questions on stackoverflow and nothing helped. I tried doing $.post instead of $.ajax and the "data" field which contains form_data is empty.

我需要这个用于Wordpress插件而我正在尝试避免使用第三方JS插件上传部分。

I need this for a Wordpress plugin and I'm trying to avoid using 3rd party JS plugins for the upload part.

推荐答案

$ _ FILES 您检查上传文件的位置不是 $ _ POST

您的代码中还实际上传了两次文件,因为它在您的表单中实例化表单数据对象,然后使用append再次添加它。
要么

$_FILES is where you check for uploaded files not $_POST.
Also in your code you actually upload the file twice as it is in the form you instantiated the form data object with then you add it again with append. Do either

var form_data = new FormData( jQuery("form#uploadForm")[0] );

var form_data = new FormData();
form_data.append( 'image', file );

这篇关于使用Ajax和Jquery上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆