文件名称使用vue前端设置utf-8乱码问题

发布时间 2023-04-17 09:50:13作者: 站着说话不腰疼

文件名称使用vue前端设置utf-8乱码问题

1、下载入口

    /**
     * @description 下载文件到前端
     * @params response
     * @params filePath 文件存放的完整路径,以文件名结尾
     *@params fileName
     * @return void
     */
    public static void downLoadFile(HttpServletResponse response, String filePath, String downloadName) throws Exception {
        File file = new File(filePath);
        String fileName = StringUtil.isEmpty(downloadName) ? file.getName() : downloadName;
        //fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); //非vue项目开启
        fileName = URLEncoder.encode(fileName,String.valueOf(StandardCharsets.UTF_8));//vue项目开启
        byte[] downFile = getBytesByFile(file);
        if (downFile != null) {
            response.reset();
            response.setCharacterEncoding("utf-8");//vue项目开启
            //response.setContentType("text/html;charset=utf-8"); //非vue项目开启
            response.addHeader("Content-type", "application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            OutputStream outputStream = null;
            outputStream = response.getOutputStream();
            outputStream.write(downFile);
            outputStream.close();
        }
    }

2、主要的实现

        String fileName = StringUtil.isEmpty(downloadName) ? file.getName() : downloadName;
        response.setCharacterEncoding("utf-8");