PHP ajax使用新数组上传多个文件

2024-05-08

它是我的上传 html 代码;

 <div class="col-xs-12">
    <label for="upload" class="btn btn-sm btn-outline green btn-block">
       <i  class="fa fa-upload"></i>
       upload
   </label><input type="file" multiple id="upload"  class="hidden"/>
 </div>

更改方法上的文件元素

 $("#upload").change(function (event) {
            var files = event.target.files;
            files = Object.values(files);
            files.forEach(function (file) {
                if (file.type.match('image')
                    || file.type.match('application/vnd.ms-excel')
                    || file.type.match('application/pdf')
                    || file.type.match('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
                    || file.type.match('application/vnd.openxmlformats-officedocument.presentationml.presentation')
                ) {
                    uploadingFile.push(file);
                }
            });
        });

点击上传按钮时的Ajax代码..

var myFormData = new FormData();
        uploadingFile.forEach(function (file) {
            myFormData.append('myFiles', file);
        });
        myFormData.append('a', 1);
        $.ajax({
            url: 'ajax/upload.php',
            type: 'POST',
            processData: false, // important
            contentType: false, // important
            data: myFormData,success: function(data, textStatus, jqXHR)
            {
              console.log(data);
            }
        });

最后的代码是 php 代码;

    $myFiles=$_FILES["myFiles"];

for($i=0; $i<count($myFiles); $i++){
    $target_path = "uploaded_files/";
    print_r($myFiles[$i]);
    echo $myFiles[$i]["tmp_name"]."\n";
    $ext = explode('.',$myFiles[$i]["tmp_name"]);
    $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];

    $sonuc=move_uploaded_file($myFiles[$i], $target_path);
    if(move_uploaded_file($myFiles[$i], $target_path)) {
        echo "The file has been uploaded successfully \n";
    } else{
        echo "There was an error uploading the file, please try again! \n";
    }
}

运行代码时我收到此消息。上传文件时出错,请重试!我想用数组将多个文件上传到服务器。为什么我需要一个数组,因为我删除了数组中的一些文件,并且我想将数组的最后结果上传到服务器。

我有什么错?我什么也没找到。

$myFiles[$i] 是一个空对象。


您正在使用这行代码附​​加单个文件myFormData.append('myFiles', file);。你必须使用这个代码myFormData.append('myFiles[]', file);发送多个文件。下面是我实现的可以上传多个文件的代码。

在您的脚本中放置以下代码。

<script type="text/javascript">
    $("#upload").change(function (event) {
        var files = event.target.files;
        var uploadingFile = [];
        files = Object.values(files);
        files.forEach(function (file) {
            if (file.type.match('image')
                || file.type.match('application/vnd.ms-excel')
                || file.type.match('application/pdf')
                || file.type.match('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
                || file.type.match('application/vnd.openxmlformats-officedocument.presentationml.presentation')
            ) {
                uploadingFile.push(file);
            }
        });

        var myFormData = new FormData();
        uploadingFile.forEach(function (file) {
            myFormData.append('myFiles[]', file);
        });

        $.ajax({
            url: 'upload.php',
            type: 'POST',
            processData: false, // important
            contentType: false, // important
            data: myFormData,success: function(data, textStatus, jqXHR)
            {
              console.log(data);
            }
        });
    });
</script>

并在您的上传 php 代码中放置以下代码。

$target_path = "uploaded_files/";

$myFiles=$_FILES["myFiles"];
if(count($myFiles['name']) > 1){
    $total = count($myFiles['name']);
    for($i=0; $i<$total; $i++){
        $ext = explode('.',$myFiles["name"][$i]);
        $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];

        if(move_uploaded_file($myFiles["tmp_name"][$i], $target_path)) {
            echo "The file has been uploaded successfully \n";
        } else{
            echo "There was an error multiple uploading the file, please try again! \n";
        }
    }
} else {
    $ext = explode('.',$myFiles["name"]);
    $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];

    if(move_uploaded_file($myFiles["tmp_name"], $target_path)) {
        echo "The file has been uploaded successfully \n";
    } else{
        echo "There was an error uploading the file, please try again! \n";
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PHP ajax使用新数组上传多个文件 的相关文章

随机推荐

  • 如何让 Casper JS 返回指示测试成功状态的退出代码?

    我希望能够进行一组 Casper JS 测试 并在成功时获得返回 0 的退出代码 在错误或测试失败时返回非零的退出代码 我想从 java 运行 casper 命令并确定测试是否通过 我遇到的问题是总是返回退出代码 0 这是发生这种情况的示例
  • “struct X typedef”与“typedef struct X”的含义是什么?

    我在现有代码库中有以下 工作 代码 在 C 和 C 之间共享的包含文件中使用 在 MSVC 2010 和 Windows DDK 上编译 struct X USHORT x typedef X PX And enum MY ENUM enu
  • Android 中未找到 PhoneGap 类错误

    我的 PhoneGap Android 应用程序遇到一些问题 到目前为止我明白了 我已经把一切都做好了 这是我所做的 在 Eclipse 中创建项目后 我在 libs 文件夹中添加了 cordova 2 2 0 jar 然后我编辑了Andr
  • bitbucket、“hg 推送”和“hg 更新”

    如果我从本地 Mercurial 存储库开始 我认为它是 主要 存储库 请原谅我的 dvcs 领主 并打算使用 bitbucket 作为备份和问题跟踪工具 我可以在本地进行所有更改repo 并执行 hg Push 将更改发送回 bitbuc
  • 循环放入和取出剪贴板,无延迟

    我正在使用以下代码将文本复制到剪贴板 System Windows Forms SendKeys SendWait c 然后我用 Clipboard GetText 从剪贴板获取文本 它工作正常 但当我循环使用剪贴板并且我得到的内容应该被下
  • 持续集成的投资回报率是多少?

    目前 我们的组织没有实行持续集成 为了让我们启动并运行 CI 服务器 我需要生成一份文档来证明投资回报 除了通过尽早发现和修复错误来节省成本之外 我很好奇我可以将其写入本文档的其他好处 节省 我喜欢 CI 的第一个原因是它有助于防止开发人员
  • 使用 Morphia 配置 Spring Boot?

    我不想利用 Spring DATA MongoDB 支持 我想利用名为 Morphia 的 MongoDB ORM https github com mongodb morphia https github com mongodb morp
  • 如何在 Angular JS 中显示以字节数组形式接收的图像

    我有一个将返回图像的服务器端应用程序 这些是响应标头 Content Disposition attachment filename 8822a009 944e 43f4 999b d297198d302a 1 0 low res Cont
  • SqlCommand返回值参数

    也许查看此代码的其他人能够告诉我为什么 returnID 始终为 0 我正在尝试从插入的记录中检索新的 ID public int AddToInventory int PartID int QtyOnHand int SpokenFor
  • 使用新数据输入自动更新图表

    我的图表从 DataGridView 加载数据 如果将新值插入到 DataGridView 中 我希望自动使用新数据更新图表 我的图表必然是table1 and table2在我的 DataGridView 中 它从 DataTable 获
  • 从 Harp.js 中的 EJS 模板调用另一个文件上的 javascript 函数

    尝试使用 Harp js 制作一个网站 我使用 ejs 模板 并希望将一些有用的 javascript 函数存储在中央文件中 我怎么做 我尝试使用 但它不起作用 似乎js文件没有被解析 有任何想法吗 谢谢 尽管有多种方法 有时 可以实现这一
  • 如何使用 javascript 选择页面上的任意文本?

    假设我有一个 contentEditablediv 用户可以编辑和更改其中的文本和元素 我如何任意更改此选择div用JavaScript 我所说的 更改 并不是指 更改用户选择的内容 我的意思是实际上更改what被选中 然后 用户应该能够在
  • 如何用C语言测量时间?

    我想知道某个代码块执行了多长时间 大约 像这样的事情 startStopwatch do some calculations stopStopwatch printf lf timeMesuredInSeconds How 您可以使用clo
  • Android 中的 ImageView 拖动限制

    我在布局中有一个 ImageView 并在 ImageView 上设置 OnTouchListener 来拖动 ImageView 它工作得很好 我的问题是如何防止将 ImageView 移动到布局范围之外 这是我的代码 活动类别 publ
  • 如何远程调试长时间运行的 python 脚本或服务?

    正如标题所说 我希望能够连接到在 Paster 或 uwsgi 下运行的 python 进程并利用 pdb 功能 Using winpdb http winpdb org 您可以像这样附加到正在运行的进程 插入 import rpdb2 r
  • 如果我将一个大函数声明为内联函数怎么办?

    我搜索了一些相关问题 例如C 中内联函数的好处 https stackoverflow com questions 145838 benefits of inline functions in c 但我还有疑问 如果内联函数只是为了 为编译
  • 通过 Selenium 捕获 JSON 响应

    我正在使用 Selenium IDE 或 webdriver 测试网页 该网页有一个 搜索 功能 基本上只是一个带参数的 GET 调用 javascript 还输出以控制台从搜索调用返回的 JSON 即类似console log data
  • CSS 3假3D立方体在2个盒子之间旋转

    我使用 css 实现了翻转旋转 flip card position relative z index 1 webkit perspective 1000px moz perspective 1000px o perspective 100
  • 如何在反应导航中将道具传递给“屏幕”/组件

    我对一般编程相当陌生 甚至对 JS 和 React Native 还比较陌生 但我已经为此工作了一整天 但我仍然没有弄清楚 所以我求助于 Stack Overflow 希望有人能帮助我可以帮我 基本上我想要完成的是设置其他Component
  • PHP ajax使用新数组上传多个文件

    它是我的上传 html 代码 div class col xs 12 div