单个文件本地服务器下载实现
service层接口定义代码
public interface IDownloadFileService {
// 单个文件下载
public void downloadFile(String fileName);
}
service层接口实现类代码
@Service
public class DownloadFileServiceImpl implements IDownloadFileService {
@Value("${file.path}")
private String FILE_ROOT_PATH;
@Override
public void downloadFile(String fileName) {
// 获取response对象
HttpServletResponse resp = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getResponse();
// 获取服务器本地的文件位置
File file = new File(FILE_ROOT_PATH + fileName);
if (file.exists()) {
BufferedInputStream bufferedInputStream = null;
BufferedOutputStream bufferedOutputStream = null;
try {
resp.setContentType("application/x-msdownload");
resp.setHeader("Content-Dispostion",
"attachment;filename=" + new String(fileName.getBytes(), "ISO-8859-1"));
FileInputStream inputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(inputStream); //缓冲流加速读
OutputStream outputStream = resp.getOutputStream();
bufferedOutputStream = new BufferedOutputStream(outputStream); //缓冲流加速写
// byte b[]=new byte[1024];
int n;
while ((n = bufferedInputStream.read()) != -1) {
// outputStream.write(b,0,n);
bufferedOutputStream.write(n);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bufferedOutputStream.close();
bufferedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
throw new RuntimeException("文件在本地服务器不存在");
}
}
}
controller层实现类代码
@RestController
@RequestMapping("/file")
public class DownLoadFileController {
@Autowired
private DownloadFileServiceImpl downloadFileServiceImpl;
@GetMapping("/downloadsinglefile")
public void downloadSingleFile(@RequestParam(value = "filename") String fileName)
{
downloadFileServiceImpl.downloadFile(fileName);
}
}
前端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>下载测试</title>
</head>
<body>
<a href="/file/downloadsinglefile?filename=xxxname" download="xxxname" >下载1 </a>
<a href="/file/downloadsinglefile?filename=8.19.jpg" download="8.19.jpg" >下载2 </a>
<a href="/file/downloadsinglefile?filename=idea文档.pdf" download="idea文档.pdf" >下载3 </a>
</body>
</html>
配置文件application.properties
server.port=8083
//本地服务器上存放需要下载的文件位置 eg: /root/git/xxxdir 我这里项目在window上就在本地测试了
file.path=C:\\Users\\wanlf\\Desktop\\\u7167\u7247\\
实现效果图
以上就是单个文件下载案例