如何让FileReader图片预上传器按文件名排序展示?
解决图片预上传按文件名排序的问题
嘿,我来帮你搞定这个排序问题~ 你遇到的情况是因为浏览器返回的FileList对象的顺序并不是固定按文件名来的,它取决于系统文件选择器的默认排序规则(比如你这里就是按文件大小排了)。要实现按文件名排序,我们需要手动把文件列表转成数组,然后做排序处理,再遍历展示。
修改后的完整代码(重点看script部分)
<html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <title>generate nama ikan</title> </head> <body> <div class="flex-center position-ref full-height"> <div class="container"> <div class="row"> <div class="col-md-12"> <h1>Nama Ikan</h1> <input id="ingambar" type="file" multiple /> </div> </div> <div class="row"> <div class="col-md-12"> <div class="content"> <br /> <table class="table"> <thead> <th>gambar</th><th>nama</th> </thead> <tbody></tbody> </table> </div> </div> </div> </div> </div> </body> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script> $('#ingambar').change(function () { // 1. 将FileList转为数组,方便排序 const filesArray = Array.from(this.files); // 2. 按文件名中的数字排序(适配img001到img100的命名规则) filesArray.sort((fileA, fileB) => { // 提取文件名里的数字部分,转成整数 const numA = parseInt(fileA.name.match(/\d+/)[0], 10); const numB = parseInt(fileB.name.match(/\d+/)[0], 10); // 按数字从小到大排序 return numA - numB; }); // 3. 遍历排序后的文件数组,生成预览内容 filesArray.forEach((file) => { const reader = new FileReader(); reader.onload = function (e) { // 修正了原代码里表格单元格的结构错误 $('tbody').append(`<tr> <td><img width="100px" src="${e.target.result}"></td> <td><input class="form-control" type="text" value="${file.name.slice(0, -4)}" name="namaikan[]" disabled/></td> </tr>`); }; reader.readAsDataURL(file); }); }); </script> </html>
关键改动说明
- 转数组排序:原生
FileList是类数组对象,没有sort方法,所以用Array.from()把它转成真正的数组,这样就能调用排序方法了。 - 数字排序逻辑:因为你的文件名是
img001到img100这种带数字后缀的,如果直接按字符串排序,img100会排在img002前面(字符串比较是逐字符比,"1"比"0"小)。所以我们用正则/\d+/提取文件名里的数字,转成整数后再比较,这样就能保证数字从小到大排列。 - 修复表格结构:原代码里的input标签没有被包裹在
<td>里,我已经修正了这个小问题,确保表格的HTML结构正确。
这样修改后,你选择img001到img100的图片,预览时就会按文件名的数字顺序展示啦~
内容的提问来源于stack exchange,提问作者Andi Haidar
相关产品推荐
相关产品推荐

