标签:vue java springboot res io org import 下载 String
//vue element-ui<el-button size="medium" type="primary" @click="download">导出</el-button> //js downLoad(){ window.location.href="/api/downLoad"; },
//后台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,java,springboot,res,io,org,import,下载,String 来源: https://www.cnblogs.com/javalinux/p/14807391.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。