admin管理员组

文章数量:1638924

解决 浏览器下载通过Controller接口下载文件,不兼容问题(实际上文件是存在的):

谷歌浏览器和Microsoft浏览器

无法下载的截图结果如下:

看看Microsoft浏览器,也是无法下载的:

同样不能下载!!!!

但是火狐和postman是可以的,

火狐浏览器下载截图如下:

使用火狐浏览器是OK的!!!!

使用postman如下:

也是OK的;

下面看源码并给出解决的方案:


@GetMapping("/downloadASingleFile")
    public void downloadASingleFile(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String path = getDownloadDir();
        Path filePath = Paths.get(path, fileName);
        if (!Files.exists(filePath)) {
            throw new FileNotFoundException("下载的文件不存在, 路径为:" + filePath);
        }
        writeFileToResponse(filePath, request, response);
    }

writeFileToResponse 方法

public void writeFileToResponse(Path filePath, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		if (!Files.exists(filePath)) {
			throw new FileNotFoundException(filePath.toString());
		}
		// 获取浏览器类型
		String browser = request.getHeader("user-agent");
		// 设置响应头,206支持断点续传
		int httpStatus = 206;
		if (browser.contains("MSIE"))
			httpStatus = 200;// 200 响应头,不支持断点续传
 		response.reset();
		response.setStatus(httpStatus);
		// 响应头
 		response.setContentType("application/octet-stream");
		File file = filePath.toFile();
		response.setHeader("Content-Disposition", "Attachment;filename=" + file.getName());// 设置下载后的名称
		response.setHeader("Content-Length", file.length() + "");
		try (FileInputStream in = new FileInputStream(file);) {
			byte[] buffer = new byte[getBufferSize()];
			int length = 0;
			while ((length = in.read(buffer)) > 0) {
				rateLimit();
				response.getOutputStream().write(buffer, 0, length);
			}
			response.getOutputStream().flush();
		} catch (IOException e) {
			throw e;
		}
		response.flushBuffer();
	}

解决办法:
修改writeFileToResponse 方法,修改之后如下:

public void writeFileToResponse(Path filePath, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		if (!Files.exists(filePath)) {
			throw new FileNotFoundException(filePath.toString());
		}
		
		// 响应头
		response.setContentType("application/octet-stream");
		File file = filePath.toFile();
		response.setHeader("Content-Disposition", "Attachment;filename=" + file.getName());// 设置下载后的名称
		response.setHeader("Content-Length", file.length() + "");
		try (FileInputStream in = new FileInputStream(file);) {
			byte[] buffer = new byte[getBufferSize()];
			int length = 0;
			while ((length = in.read(buffer)) > 0) {
				rateLimit();
				response.getOutputStream().write(buffer, 0, length);
			}
			response.getOutputStream().flush();
		} catch (IOException e) {
			throw e;
		}
		response.flushBuffer();
	}

解决之后:

谷歌浏览器下载成功!!

Microsoft浏览器下载成功!!!

当然,在修改之后火狐浏览器依然兼容,这就解决了不兼容的问题。!!!!

本文标签: 浏览器文件火狐无法下载不兼容