vue+springboot文件下载
2021/5/25 10:24:59
本文主要是介绍vue+springboot文件下载,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
![复制代码](/images/baidian.png)
//vue element-ui<el-button size="medium" type="primary" @click="download">导出</el-button> //js downLoad(){ window.location.href="/api/downLoad"; },
![复制代码](/images/baidian.png)
![复制代码](/images/baidian.png)
//后台java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DownLoadFile {
private static Logger log = LoggerFactory.getLogger(DownLoadFile.class);
@RequestMapping(value = "/downLoad", method = RequestMethod.GET)
public static final String downLoad(HttpServletResponse res) throws UnsupportedEncodingException {
Map<String, Object> reMap = new HashMap<>();
//文件名 可以通过形参传进来
String fileName = "t_label.txt";
//要下载的文件地址 可以通过形参传进来
String filepath = "f:/svs/" + fileName;
OutputStream os = null;
InputStream is = null;
try {
// 取得输出流
os = res.getOutputStream();
// 清空输出流
res.reset();
res.setContentType("application/x-download;charset=GBK");
res.setHeader("Content-Disposition",
"attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso-8859-1"));
// 读取流
File f = new File(filepath);
is = new FileInputStream(f);
if (is == null) {
reMap.put("msg", "下载附件失败");
}
// 复制
IOUtils.copy(is, res.getOutputStream());
res.getOutputStream().flush();
} catch (IOException e) {
reMap.put("msg", "下载附件失败,error:" + e.getMessage());
}
// 文件的关闭放在finally中
finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
log.error(e.toString());
}
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
log.error(e.toString());
}
}
String str = JsonUtil.map2Json(reMap);
return str;
}
}
转自:https://www.cnblogs.com/xuchao0506/p/12681480.html
这篇关于vue+springboot文件下载的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)