【问题标题】:How to use both id and name in multiple image upload?如何在多张图片上传中同时使用 id 和 name?
【发布时间】:2019-10-15 17:07:18
【问题描述】:
<input class="form-control" type="file" id="pro-image" name="image[]" multiple>

当 Id 这次成功工作时,名称没有捕获图像路径。

这意味着空数组。
但是当删除 Id 时,只需使用 name="image[]" 成功提交值。

【问题讨论】:

  • 请提供您的代码
  • 您在使用表单吗?你是如何发布图片的?

标签: php html laravel


【解决方案1】:

假设你有一个表单,你可以像这样使用 fetch API 通过 Ajax 提交图像

<form action="/" method="post" enctype="multipart/form-data">
    @csrf
    <input class="form-control" type="file" id="pro-image" name="image[]" multiple>
    <button type="submit">Submit</button>
</form>

<script>
    let form = document.forms[0];
    form.onsubmit = (event) => {
        event.preventDefault();
        fetch('/', {
            method: 'POST',
            credentials: "same-origin",
            body: new FormData(form),
        });
    }
</script>

然后像这样返回图像的路径数组

Route::post('/', function () {
    $images = request()->file('image');
    $paths = [];
    foreach ($images as $image) {
        $paths[] = $image->store('/public');
    }
    return $paths;
});

不用表单,听输入变化

<meta name="csrf-token" content="{{ csrf_token() }}">
<input class="form-control" type="file" id="pro-image" name="image[]" multiple onchange="submit()">

<script>
    function submit() {
        var ins = document.getElementById('pro-image').files.length;
        var fd = new FormData();
        for (var x = 0; x < ins; x++) {
            fd.append("pro-image[]", document.getElementById('pro-image').files[x]);
        }
        fetch('/', {
            headers: {
                "Accept": "application/json",
                "X-Requested-With": "XMLHttpRequest",
                "X-CSRF-Token": document.querySelector('meta[name="csrf-token"]').content
            },
            method: 'POST',
            credentials: "same-origin",
            body: fd,
        });
    }
</script>

从后端访问

Route::post('/', function () {
    $images = request()->file('pro-image');
    $paths = [];
    foreach ($images as $image) {
        $paths[] = $image->store('/public');
    }
    return $paths;
});

现在您可以在开发工具的网络选项卡上查看公共目录中存储图像的路径

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-07
    • 2016-10-12
    • 2015-01-31
    • 1970-01-01
    • 2020-04-21
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多