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下载文件

posted @ 2020-04-10 19:28  Gyyyang  阅读(2449)  评论(2编辑  收藏  举报