• Java下载服务器文件到前端


    直奔主题!

    Java代码

    /**
    * 下载文件
    * @param path
    * @param fileName
    * @param response
    */
    public static void downLoad(String path, String fileName,HttpServletResponse response) {
    	// 服务器保存的文件地址,即你要下载的文件地址(全路径)
    	File file = new File(path);
    	InputStream inputStream = null;
    	OutputStream outputStream = null;
    	try {
    		inputStream = new BufferedInputStream(new FileInputStream(file));
    		byte[] buffer = new byte[inputStream.available()];
    		inputStream.read(buffer);
    		response.reset();
    		response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
    		response.addHeader("Content-Length", "" + file.length());
    		response.setContentType("application/octet-stream");
    		outputStream = new BufferedOutputStream(response.getOutputStream());
    		outputStream.write(buffer);
    		outputStream.flush();
    	}
    	catch (IOException e) {
    		e.printStackTrace();
    		throw new GGException(e.getMessage());
    	}
    	finally {
    		try {
    			if (outputStream != null) {
    				outputStream.close();
    			}
    			if (inputStream != null) {
    				inputStream.close();
    			}
    		}
    		catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    }
    

    前端代码

    // 下载文件
    function downLoad(sid, fileName) {
        var url = "/file/downFileBySid?sid=" + sid;
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = "blob";
        xhr.onload = function() {
            if (this.status === 200) {
                debugger
                var blob = this.response;
                var reader = new FileReader();
                reader.readAsDataURL(blob);
                reader.onload = function(e) {
                    var a = document.createElement('a');
                    a.download = fileName;
                    a.href = e.target.result;
                    $('body').append(a);
                    a.click();
                }
            } else {
                alert("下载失败");
            }
        };
        xhr.send();
    }
    

    最开始用jqueryajax发起请求,直接在response中返回的是文件流,没有blob类型返回格式。
    苦恼了好半天,希望大家别走弯路。
    如果你用swagger测试请求会直接给你生成一个下载连接,它自己内部处理了,但我们只能依赖a链接形式。
    附一个比较好的类似文章,供大家参考。Java下载文件

  • 相关阅读:
    RESTful API设计指南
    Ubuntu16.04 安装openssl
    shell while循环
    linux awk
    vim与shell切换
    shell for循环
    css 固定宽度,自动换行
    php-fpm 与 cgi
    ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/usr/local/mysql/tmp/mysql.sock'
    linux ps 命令参数详解
  • 原文地址:https://www.cnblogs.com/gyyyblog/p/12675594.html
Copyright © 2020-2023  润新知