java后台返回文件流下载文件,监听文件下载结束,实现下载前提示,文件传输完后关闭提示框效果!

java处理一般的文件下载都是直接文件流,可以达到浏览器自动弹出下载窗口的效果,如果是文件比较大或者后台处理逻辑用时比较长,为了页面更加友好,需要添加“遮罩层友情提示”,主要问题就是监听到文件传输完毕,此时需要使用fetch来实现,只改前台js即可,后台代码不用修改。

一般文件下载js代码:

点击按钮触发

function downLoadZip(){
    var url = "<%=basePath%>****downLoadZip.action";	
}

现实友情提示效果代码:

function downLoadZip(){
    //打开提示框
		layer.msg("后台正在生成打包中...",{
					icon:16,
					shade: [0.5, '#f5f5f5'],
					time:-1
				});
	var url = "<%=basePath%>********downLoadZip.action";	
	fetch(url, {
	method: 'GET',
	headers: {'Content-Type': 'application/json'},
	//body: '<请求参数:json字符串>',
}).then(res => res.blob()).then(data => {
	var blobUrl = window.URL.createObjectURL(data);
	downloads(blobUrl);
});
		}
		

function downloads(blobUrl) {
    //关闭提示框
    layer.closeAll();
	const a = document.createElement('a');
	a.style.display = 'none';
	a.download = '****报名登记表.zip';
	a.href = blobUrl;
	a.click();
	document.body.removeChild(a);
}

后台方法保持不变:

public void downLoadZip() throws Exception {
		//系统逻辑处理 。。。。。。
        //生成pdf 压缩zip 
		downLoadFile("***", "***.zip");

	}
public void downLoadFile(String pathdir, String fileName) throws IOException {

		String realpathdir = ServletActionContext.getRequest().getSession()
				.getServletContext().getRealPath(pathdir + fileName);

		HttpServletResponse response = (HttpServletResponse) ServletActionContext
				.getResponse();

		response.setContentType("application/zip");
		response.setHeader("Content-disposition", "attachment;filename="
				+ new String("*****报名登记表.zip".getBytes("gb2312"),
						"ISO8859-1"));
		File file = new File(realpathdir);

		ServletOutputStream sops = response.getOutputStream();
		FileInputStream fis = new FileInputStream(file);
		copyStream(fis, sops, true);
		fis.close();
		sops.close();
		fis = null;
		sops = null;
		file = null;

	}
private final long copyStream(InputStream source, OutputStream dest,
			boolean flush) {
		int bytes;
		long total = 0l;
		byte[] buffer = new byte[2048];
		try {
			while ((bytes = source.read(buffer)) != -1) {
				if (bytes == 0) {
					bytes = source.read();
					if (bytes < 0)
						break;
					dest.write(bytes);
					if (flush)
						dest.flush();
					total += bytes;
				}
				dest.write(buffer, 0, bytes);
				if (flush)
					dest.flush();
				total += bytes;
			}

		} catch (IOException e) {
			 throw new RuntimeException("IOException caught while copying.",e);
		}
		return total;
	}

 

  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这个问题比较复杂,因为涉及到后端的代码以及对HDFS文件系统的操作。以下是一个简单的示例,供参考: 1. 后端代码(使用Spring框架) ``` // 文件上传 @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public String upload(@RequestParam("file") MultipartFile file) { try { FileSystem fs = FileSystem.get(new Configuration()); String fileName = file.getOriginalFilename(); Path filePath = new Path("/" + fileName); FSDataOutputStream outputStream = fs.create(filePath); outputStream.write(file.getBytes()); outputStream.close(); fs.close(); return "上传成功"; } catch (Exception e) { e.printStackTrace(); return "上传失败"; } } // 文件列表展示 @RequestMapping(value = "/listFiles", method = RequestMethod.GET) @ResponseBody public List<String> listFiles() { try { FileSystem fs = FileSystem.get(new Configuration()); FileStatus[] fileStatuses = fs.listStatus(new Path("/")); List<String> fileList = new ArrayList<>(); for (FileStatus status : fileStatuses) { if (!status.isDirectory()) { fileList.add(status.getPath().toString()); } } fs.close(); return fileList; } catch (Exception e) { e.printStackTrace(); return null; } } // 文件下载 @RequestMapping(value = "/download", method = RequestMethod.GET) public ResponseEntity<Resource> download(@RequestParam("fileName") String fileName) { try { FileSystem fs = FileSystem.get(new Configuration()); Path filePath = new Path("/" + fileName); FSDataInputStream inputStream = fs.open(filePath); byte[] bytes = IOUtils.toByteArray(inputStream); inputStream.close(); fs.close(); ByteArrayResource resource = new ByteArrayResource(bytes); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"") .body(resource); } catch (Exception e) { e.printStackTrace(); return null; } } // 文件删除 @RequestMapping(value = "/delete", method = RequestMethod.DELETE) @ResponseBody public String delete(@RequestParam("fileName") String fileName) { try { FileSystem fs = FileSystem.get(new Configuration()); Path filePath = new Path("/" + fileName); boolean result = fs.delete(filePath, false); fs.close(); if (result) { return "删除成功"; } else { return "删除失败"; } } catch (Exception e) { e.printStackTrace(); return "删除失败"; } } ``` 2. 端代码(使用Vue.js框架) ``` <template> <div> <h2>文件列表</h2> <table> <thead> <tr> <th>文件名</th> <th>操作</th> </tr> </thead> <tbody> <tr v-for="file in fileList" :key="file"> <td>{{ file }}</td> <td> <button @click="downloadFile(file)">下载</button> <button @click="deleteFile(file)">删除</button> </td> </tr> </tbody> </table> <h2>文件上传</h2> <input type="file" ref="fileInput" /> <button @click="uploadFile">上传</button> </div> </template> <script> import axios from 'axios' export default { data() { return { fileList: [] } }, mounted() { this.listFiles() }, methods: { listFiles() { axios.get('/listFiles').then(response => { this.fileList = response.data }) }, uploadFile() { const formData = new FormData() formData.append('file', this.$refs.fileInput.files[0]) axios.post('/upload', formData).then(() => { this.listFiles() }) }, downloadFile(fileName) { axios.get('/download', { params: { fileName: fileName }, responseType: 'blob' }).then(response => { const url = window.URL.createObjectURL(new Blob([response.data])) const link = document.createElement('a') link.href = url link.setAttribute('download', fileName) document.body.appendChild(link) link.click() }) }, deleteFile(fileName) { axios.delete('/delete', { params: { fileName: fileName } }).then(() => { this.listFiles() }) } } } </script> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值