formdata上传多个图片,为什么不能遍历

for(var _img in img_file){           
    formdata.append('file', img_file[_img]);
}
let files = ctx.request.files;
console.log('files+++:');console.log(files);
    for(let index in files){
        console.log(index);//输出file[]
        file = files[index];
        console.log('file---:')
        console.log(file)

console.log(index);//输出file[]
而且files、files[index]是同一个东西
为什么?
图片描述

图片描述

阅读 2.2k
2 个回答

FormData不能通过实例的[]或者.获取属性,只能通过get
比如

let form = new FormData()
form.append('prop', 1)
console.log(form.prop)//undefined
console.log(form.get('prop'))

如果需要获得所有的字段,通过keys,values等api获得一个伪数组再操作

解决了

function upload(files,title){  
    let imgList=[],file,url;
    
    files = files['file'];//关键!!!!!!
    
    if(files.length){//如果是一个数组
        for(let index in files){
            file = files[index];     

            url=`uploads/${title}-${file.name}`;
            fs.createReadStream(file.path).pipe(fs.createWriteStream(url))
        
            imgList.push([index,url]);
        }
    }else{   
        file = files;        
        url=`uploads/${title}-${file.name}`;
        fs.createReadStream(file.path).pipe(fs.createWriteStream(url))
        imgList.push([0,url]);
    }
     
     return imgList;
   
}
exports.add = async(ctx, next)=>{
    let {title,body,tags,category}=ctx.request.body;
    let files = ctx.request.files;//重点

    let imgList = upload(files,title);

    let post = new Post({
        title,
        body,
        tags,
        category,
        imgList
    })
    let result= await dbHelper.Save(post);
    ctx.response.body = result;    
}
推荐问题