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

原文地址:https://www.cnblogs.com/gyyyblog/p/12675594.html

时间: 2024-08-29 18:59:21

Java下载服务器文件到前端的相关文章

通过浏览器下载服务器文件(日志)

下载服务器的文件是经常需要进行的操作. 可以通过FTP工具进行(如Filezilla等). 以下提供一种通过浏览器下载服务器文件的黑科技: 1. 在windows/linux/solaris(下载文件所在环境) 随便一个目录下运行:(要安装python) python -m SimpleHTTPServer [port] 可选,默认8000 linux-cd03:/opt # python -m SimpleHTTPServerServing HTTP on 0.0.0.0 port 8000

java web服务器文件的下载(有下载弹出匡)

昨天做了一个文件从服务下载的功能,怎么都不弹出页面,下载框.后查询得知.目前两种方法 1.<a href='下载路径' /> 2.window.location.href = basePath + "downloadTemplate.do?template=huiyuan"; 通过 这两种方式可以有这种弹出窗 希望能帮助,遇到和我一样问题的朋友~ 附下载的工具类,可直接复制可用 public void downloadFile(String filePath,String

Java下载https文件上传到阿里云oss服务

今天做了一个从Https链接中下载音频并且上传到OSS服务器,记录一下希望大家也少走弯路. 一共两个类: 1 实现自己的证书信任管理器类 /** * @author mazhq * @Title: X509TrustUtiil * @ProjectName: zeus * @Description: 证书信任管理器类 * @date 2019/2/18 15:14 */ public class X509TrustUtil implements X509TrustManager { @Overr

下载服务器文件到本地

1,使用CRT连接服务器 2,连接SFTP 3,将要下载的文件复制到当前用户的  "家" 目录下 4,使用get下载文件

Linux命令行上传本地文件到服务器 、 下载服务器文件到本地

sh使用命令: scp 将本地文件上传至服务器 第一个是本地文件的路径/文件名, 例如 ./index.tar.gz  . index.html . bg.png 等 第二个是要上传到的服务器的位置  例如  root@39.106.144.90:/var/www scp path/filename userName@sseverName:path 如果是要下载服务器的文件到本地 则调换两个位置就可以 scp userName@sseverName:path path/filename 如果操作

java下载服务器上的文件

//文件路径 File file = new File(path); // 取得文件名. String filename = file.getName(); // 以流的形式下载文件. InputStream fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response

用java下载hdfs文件报NullPointerException

用fs.copyToLocalFile( hdfsPath,localPath);下载hdfs的文件会报NullPointerException,具体报错为: java.lang.NullPointerException at java.lang.ProcessBuilder.start(ProcessBuilder.java:1012) at org.apache.hadoop.util.Shell.runCommand(Shell.java:487) at org.apache.hadoop

【小坑】java下载excel文件

excel文件的导入导出是很常见的功能,这次做了个下载的功能,踩了一些坑,记下来避免以后重复踩…… 1.inputstream序列化问题 Could not write JSON document: No serializer found for class java.io.FileDescriptor and no properties discovered to create BeanSerializer 客户端调取服务端上传,从前台获取的file文件中拿到inputstream,做一些判断

WebClient实现下载txt文件并与用户输入进行匹配

/// <summary> /// 验证 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { //WebClient client = new WebClient(); //byt