html5 多图上传 input 一次上传多个文件

直接贴完整代码,这个删除的时候用到了jquery,预览是不需要jq的,这里面有个bug,就是添加上传的时候,新的图片会循环好几次,前端不太好,希望有人可以修复一下,这个是多图只请求一次后端接口。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
    .imgList {
        position: relative;
        display: inline-block;
    }

    .imgList .remove {
        display: block;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, .7);
    }

    </style>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
    <div class="form-group">
        <label for="title" class="col-xs-4 col-sm-2 control-label"><span style="color:red;">*&nbsp;</span>预览图片&nbsp;:</label>
        <div class="col-xs-8 col-sm-9">
            <input id="load" type="file" class="btn btn-primary" name="pictures[]" accept="image/png, image/jpeg" onchange="upload(this.files)" multiple/>
            <div id="huixian"></div>
            文件类型只能是jpg,jpeg,png中的一种 !且总大小不能超过 10 M。
        </div>
    </div>
</body>
<script type="text/javascript">
function getobj(obj) { return document.getElementById(obj); }
var str = "";
var imgArr = [];

function upload(f) {
    for (var i = 0; i < f.length; i++) {
        imgArr = [];
        var reader = new FileReader();
        reader.readAsDataURL(f[i]);
        imgArr.push[f];
        reader.onload = function(e) {
            str += '<div class="imgList"><span class="remove">remove</span><img class="img" src="' + e.target.result + '"/ style="width:100px;margin:0 5px 0 5px"></div>';
            getobj("huixian").innerHTML = str;
        }
    }
}
$("#huixian").off("click").on("click", ".remove", function() {
    $(this).parent().remove();
    imgArr.splice(0, $(this).parent().index(".imgList"));
})

</script>

</html>

附上后端laravel代码:

   /**
     * 多文件上传,一次最多上传10个文件
     * @param  [type] $imageArray [description]
     * @param  [type] $path       [description]
     * @return [type]             [description]
     */
    public function multiUpload($imageArray, $path = '')
    {
        set_time_limit(400);
        if (!$imageArray || count($imageArray) > 10) {
            return false;
        }
        $new_image_array = [];
        foreach ($imageArray as $key => $value) {
            $new_image_array[] = $value->store($path);#本地上传
            // $new_image_array[] = $value->store($path, 'ftp');#ftp上传
        }
        return $new_image_array;
    }

你没看错,就是这么简单如果需要过滤文件类型,可以使用validation,也是一两行代码即可。
这里写图片描述

猜你喜欢

转载自blog.csdn.net/zhezhebie/article/details/80582511