admin管理员组

文章数量:1535137

java下载文件到浏览器默认路径

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog./mengmeng2222222

一、controller层代码:

@RequestMapping("/downExcel")

@ResponseBody

public Object downExcel(){

try {

File file=ResourceUtils.getFile("classpath:doc"); //获取resources下面的doc下面的文件

File[] files=file.listFiles();

return FileUtil.downloadFile(files[0]); //files[0]是要下载到默认浏览器路径的文件

} catch (Exception e) {

return MarkUtil.markRetunMsg(false,"下载失败");

}

}

注释:运用spring中的ResourceUtils.getFile读取jar包内文件,也就是获取的是下图中的文件

二、FileUtil类中的downloadFile方法如下:

/**

* 文件下载

* @param file

* @throws IOException

*/

public static ResponseEntity downloadFile(File file) throws IOException {

if (file.exists()) {

FileSystemResource fileSource = new FileSystemResource(file);

return downloadFile(fileSource.getInputStream(),fileSource.getFilename());

}

return null;

}

public static ResponseEntity downloadFile(InputStream in,String fileName) {

try {

byte[] testBytes = new byte[in.available()];

HttpHeaders headers = new HttpHeaders();

headers.add("Cache-Control", "no-cache, no-store, must-revalidate");

headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", MarkUtil.convertFileName(fileName)));

headers.add("Pragma", "no-cache");

headers.add("Expires", "0");

return ResponseEntity

.ok()

.headers(headers)

.contentLength(testBytes.length)

.contentType(MediaType.parseMediaType("application/octet-stream"))

.body(new InputStreamResource(in));

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

三、MarkUtil类中的convertFileName方法如下:

/**

* chinese code convert

* @param fileName

* @return

*/

public static String convertFileName(String fileName) {

if(isContainChinese(fileName)) {

try {

fileName = URLEncoder.encode(fileName, "UTF-8");

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

}

return fileName;

}

亲测有效!!!!!如果对你有帮助了,一定要点个赞哇,整理不易。

可以转载,但是务必加上来源,谢谢!

本文标签: 路径浏览器文件Java