用ajax下载csv格式的文件

前端:是用到了a标签的download属性,URL对象可以为Blob对象生成一个网络地址,转换成gb2312格式,防止打开乱码

export const downLoadFile = (fileName="myFile.csv", str) => {
   let csvString = new Blob([`\ufeff${str}`], { type: 'text/plain;charset=gb2312;' }),
       a = document.createElement('a');
   a.href = URL.createObjectURL(csvString);
   a.target      = '_blank';
   a.download    = fileName;
   document.body.appendChild(a);
   a.click();
}

后端:导出二维数组为csv格式并转换成gb2312输出

function exportCSV($titles, $contents) {
    header("Content-type: text/csv; charset=gb2312");
    $output = fopen('php://output', 'w');
    for ($i=0;$i$titles);$i++) {
        $titles[$i] = mb_convert_encoding($titles[$i], "GB18030", "UTF-8, GB18030");
    }
    fputcsv($output, $titles);
    foreach ($contents as $k=>$item) {
        foreach($item as $k2=>$value){
            $contents[$k][$k2] = mb_convert_encoding($contents[$k][$k2], "GB18030", "UTF-8, GB18030");
        }
    }
    foreach ($contents as $key2) {
        fputcsv($output, $key2);
    }
    unset($aData);
}

你可能感兴趣的:(javascript)