zoukankan      html  css  js  c++  java
  • springboot下载文件(使用流)

    1.FileServiceImpl.java

    /**
    	 * 下载文件
    	 * 
    	 * @param address
    	 * @param response
    	 * @throws IOException
    	 */
    	@Override
    	public void downloadFile(String address, HttpServletResponse response) throws IOException {
    		if (address.contains("%")) {
    			try {
    				address = URLDecoder.decode(address, "UTF-8");
    			} catch (UnsupportedEncodingException e) {
    				throw new CyException("文件路径有误");
    			}
    		}
    		ServletOutputStream out = null;
    		FileInputStream in = null;
    		try {
    			in = new FileInputStream(new File(address));
    			String[] dir = address.split("/");
    			String fileName = dir[dir.length - 1];
    			// 设置响应类型为html,编码为utf-8,处理相应页面文本显示的乱码
    			response.setContentType("application/octet-stream");
    			// 设置文件头:最后一个参数是设置下载文件名
    			response.setHeader("Content-disposition", "attachment;filename=" + fileName);
    			out = response.getOutputStream();
    			// 读取文件流
    			int len = 0;
    			byte[] buffer = new byte[1024 * 10];
    			while ((len = in.read(buffer)) != -1) {
    				out.write(buffer, 0, len);
    			}
    			out.flush();
    		} catch (FileNotFoundException e) {
    			throw new CyException("文件路径有误");
    		} finally {
    			response.flushBuffer();
    			try {
    				out.close();
    				in.close();
    			} catch (NullPointerException e) {
    				throw new CyException("responseFileStream stream close() error:NullPointerException" + e.toString());
    			} catch (Exception e) {
    				throw new CyException("responseFileStream stream close() error:" + e.toString());
    			}
    		}
    
    	}
    

    2.FileController.java

    @RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
    	@ResponseBody
    	@Validated
    	public void downloadFile(@NotBlank @RequestParam(value = "address") String address, HttpServletResponse response)
    			throws IOException {
    		fileService.downloadFile(address, response);
    	}
    
     
     转自:https://www.cnblogs.com/xian-yu/p/13267312.html
  • 相关阅读:
    matlab 画图中线型及颜色设置
    创建二叉树求叶子节点个数
    乐视2016暑期实习编程题
    MFC特定函数的应用20160720(SystemParametersInfo,GetWindowRect,WriteProfileString,GetSystemMetrics)
    MFC使用ShowWindow(SW_MAXIMIZE)任务栏消失的处理
    Windows字符集的统一与转换
    MFC学习20160718(GetModuleFileName&&GetAppDataPath)
    泛型算法概述
    链表的特有算法操作
    流迭代器的使用
  • 原文地址:https://www.cnblogs.com/javalinux/p/15665883.html
Copyright © 2011-2022 走看看