select 并在客户端上传多张照片

select and upload multiple photos client side

我正在尝试使用此代码从我的计算机上传图片

var filesValues = []

$(photosbtn).click(function() {
    photos.click()

    $(photos).change((e) => {

    const file  = e.target.files[0];

 if (file){

 filesValues.push(file)

console.log(filesValues)
}

}}

现在如果我 select 一个文件结果是一个这样的文件

0: File {name:"130492893_1475704719298017_6321765405148113863_n.jpg", lastModified: 1607806703000, lastModifiedDate: Sat Dec 12 2020 22:58:23 GMT+0200 (Eastern European Standard Time), webkitRelativePath: "", size: 17124, …}length: 1__proto__: Array(0)

但如果我再次 select 结果变成 [第一张图片,第二张图片,第二张图片] 它会像那样重复最后一个文件

0: File {name: "130492893_1475704719298017_6321765405148113863_n.jpg", lastModified: 1607806703000, lastModifiedDate: Sat Dec 12 2020 22:58:23 GMT+0200 (Eastern European Standard Time), webkitRelativePath: "", size: 17124, …}

1: File {name: "WhatsApp Image 2020-09-21 at 6.41.36 AM.jpeg", lastModified: 1600663313303, lastModifiedDate: Mon Sep 21 2020 06:41:53 GMT+0200 (Eastern European Standard Time), webkitRelativePath: "", size: 61490, …}

2: File {name:"WhatsApp Image 2020-09-21 at 6.41.36 AM.jpeg", lastModified: 1600663313303, lastModifiedDate: Mon Sep 21 2020 06:41:53 GMT+0200 (Eastern European Standard Time), webkitRelativeP

如果我再 select 一个,最后一个将重复三次,依此类推。

请问有什么解决办法?

不要这样做:

filesValues.push ...

试试这个方法:

var files = new FormData();
files.append(firstFile);
files.append(secondFile);

我找到了答案,就是这样

var filesValues = []

$(photosbtn).click(function() {
    photos.click()
})

    $(photos).change((e) => {

    const file  = e.target.files[0];

 if (file){

 filesValues.push(file)

console.log(filesValues)
})

我们不应该将 (.change) 函数放在 (.click) 函数中。