WeChat H5 download file, WeChat browser can not download file solution

When WeChat on the mobile phone accesses the webpage, it is forbidden to download files directly

However, the IOS side can preview files in .txt/.doc/.docx/.xls/xlsx/.pdf and other formats, and when the Android side downloads files in these formats, it can evoke the prompt "I am about to leave WeChat, open it in the browser"
insert image description here
so , according to these limitations of mobile phone WeChat, consider when downloading files, so that Android WeChat can evoke a prompt to open the browser to download files when downloading files of any format

1. Web code

It is recommended to implement it in the way of jumping (note: when leaving WeChat and opening it in the browser, the link address will not be modified)

function download(id){
    
    
	//例如  http://localhost/app/file/download?id=123
	let url = BASEURL +'/file/download?id='+ id;
	window.location.href = url
}

2. Java code

Judging the browser information of the client in the java program to determine whether it is mobile phone WeChat or Android WeChat
Here use JFinal

	public void download() throws IOException {
    
    
        String id = getPara("id", "");
        if(StringUtils.isNotBlank(id)){
    
    
            Record fileRec = Db.findById("file_upload", id);
            //微信端返回一个默认假文件,使得唤起微信的‘在浏览器打开’
            if(isAndroidWechat(getRequest())){
    
    
                File file = new File("a.txt");
                if(!file.exists())
                    file.createNewFile();
                renderFile(file);
            }else{
    
    
                renderFile(new File(fileRec.getStr("save_path")), fileRec.getStr("file_name"));
            }
        }else{
    
    
            renderJson(err());
        }
    }


    /**
     * 客户端是否是Android微信浏览器
     * @param request
     * @return
     */
    public static boolean isAndroidWechat(HttpServletRequest request) {
    
    
        String userAgent = request.getHeader("user-agent");
        return userAgent != null 
            && userAgent.toLowerCase().indexOf("micromessenger") > -1
            && userAgent.toLowerCase().indexOf("wxwork") < 0
            && userAgent.toLowerCase().indexOf("android") > -1;
    }
    

Guess you like

Origin blog.csdn.net/qq_42049516/article/details/129874800