【问题标题】:how can I read FormData file in php?如何在 php 中读取 FormData 文件?
【发布时间】:2016-08-15 13:28:24
【问题描述】:

我有一个 ajax 表单数据

<form id="form" action="index.php?id=upload" method="post" enctype="multipart/form-data">

    <input id="files" multiple="true" name="files[]" type="file" />

</form>

我想依次通过数据表单发送此表单。

所以我创建了一个循环 jn jquery 来读取每个文件,所以每个文件我都有这个:

var data = new FormData();
        data.append(file.name, file);

        $.ajax({
            url: 'index.php?id=upload',
            type: 'POST',
            contentType: false,
            cache: false,
            processData:false,
            data: data,
            fileName:'files',

当我在 php 代码中打印 var_dumb($_FILES) 我得到这个结果:

名称:"array(1) { ["8_modem_pool_with_small_and_big_jpg"]=> array(5) { ["name"]=> string(35) "8 调制解调器池 和 big.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> 字符串(24) "F:\xampp\tmp\php268B.tmp\"
["错误"]=> int(0) ["size"]=> int(99790) }}

如何在服务器端获取$_FILES 值? 我试试

if(isset($_FILES["files"]))
        { 

if(isset($_FILES["file"]))
        {

但它们都不起作用。

-------编辑-------------

感谢您的回答。但它们不是我的答案。

我使用时在php中

$_FILES["files"]

我得到这个错误:

未定义索引

但我可以通过这段代码打印值:

foreach($_FILES as $index => $file) {
 move_uploaded_file($file['tmp_name'],$target.$file['name']); 
}

希望你能理解我....

我想要这样的东西:

if(isset($_FILES["files"]))
{
   //do action for single file
   // do action for array file
}

最新代码适用于普通表单,但不适用于表单数据。

【问题讨论】:

标签: php jquery forms multipartform-data


【解决方案1】:

您可以尝试使用 for 循环遍历这个 3 级关联数组:

if(isset($_FILES['8_modem_pool_with_small_and_big_jpg'])){
    for($i=0;$i < count($_FILES['8_modem_pool_with_small_and_big_jpg']['name']);$i++){
        //Do whatever with the file:
        echo $_FILES['8_modem_pool_with_small_and_big_jpg']['name'][$i];
        echo $_FILES['8_modem_pool_with_small_and_big_jpg']['type'][$i];
        echo $_FILES['8_modem_pool_with_small_and_big_jpg']['tmp_name'][$i];
    }
}

【讨论】:

  • 我的问题是$_FILES['files'] ...它返回“未定义索引”错误
  • @elize 你试过$_FILES['8_modem_pool_with_small_and_big_jpg'] 吗?
  • 谢谢。你的评论就是我的答案。对于自定义名称,我这样做并且现在可以使用。 data.append('files',file);
【解决方案2】:

这取决于你想要什么值。所有这些都在数组中可见。

如果你想要名字,你可以使用

$_FILES['names']['8_modem_pool_with_small_and_big_jpg']['tmp_name']

要将文件存储到您可以使用的特定位置

move_uploaded_file( $_FILES['names']['8_modem_pool_with_small_and_big_jpg']['tmp_name'], $myFile);

【讨论】:

    【解决方案3】:

    尝试以下方法:

    move_uploaded_file( $_FILES['names']['8_modem_pool_with_small_and_big_jpg']['tmp_name'], $target);//target is the new file location and name
    

    多个文件使用循环

    foreach($_FILES['names'] as $index => $file) {
         $target = '/img/'.$file['name']
         move_uploaded_file( $file['tmp_name'], $target);
    }
    

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 2021-06-14
      • 2020-08-25
      • 2015-08-01
      • 2017-11-05
      • 2019-06-07
      • 2016-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多