springboot从服务器下载文件,代码干货
今天给大家分享一个springboot从服务器下载文件的方法,话不多说直接上代码:
controller层代码
@RequestMapping("/download")
public Map<String,String> download(HttpServletRequest request,HttpServletResponse response,String fileName) throws UnsupportedEncodingException {
Map<String,String> map = new HashMap<>();
String rootPath = System.getProperty("user.dir")+"\\src\\main\\resources\\uploadFile\\";//存储文件的目录
String FullPath = rootPath + fileName;//文件的位置
File packetFile = new File(FullPath);
String fn = packetFile.getName(); //下载的文件名
System.out.println("filename:"+fn);
File file = new File(FullPath);
// 如果文件名存在,则进行下载
if (file.exists()) {
// 配置文件下载
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 下载文件能正常显示中文
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 实现文件下载
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("Download the song successfully!");
} catch (Exception e) {
System.out.println("Download the song failed!");
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
} else {//对应文件不存在
map.put("result","failed");
return map;
}
}
前端代码
function downloadFile(fileName){
window.open("/meeting/download?fileName="+fileName);
}
以上便是关于springboot从服务器下载文件的代码,大家学会了吗,如果还有问题可在评论区留言~
共同学习,写下你的评论
评论加载中...
作者其他优质文章