1。 第一种方法是前后端的接口只给了一个API请求:
前端第一种实现方式:
<a href="/downloadfilerouter" download></a>
*备注: download属性只支持firefox, chrome,不支持IE*
前端第二个实现是使用一个div标签,使用click事件,创建一个a标签
<div name="downloadfile"
onclick="downloadFileFunction()">DownLoader</div>
function downloadFileFunction() {
let a = document.createElement('a');
a.href = '/downloadfilerouter';
a.click();
}
后端使用nodejs,我在这里把下载的文件固定了,也可以自己传人一个变量进入,在这里需要导入两个模块
var fs = require('fs');
var path = require('path');
router.get('/downloadfilerouter', function (req, res, next) {
var filename = 'desktop.ini';
var filepath = path.join(__dirname, '../uploader/' + filename);
var stats = fs.statSync(filepath);
if (stats.isFile()) {
res.set({
'Content-Type': 'application/octet-stream',
'Content-Disposition': 'attachment; filename=' + filename,
"Content-Length": stats.size
});
fs.createReadStream(filepath).pipe(res);
} else {
res.end(404);
}
});
**在firefox中,
'Content-Disposition': 'attachment; filename=' + filename,文件名不能正常显示
修改为以下代码:
"content-disposition", "attachment;filename*=UTF-8''"+ filename
**
2。第二种是定义的接口不是下载文件的路径,而是通过API可以获得文件的内容,由前端把内容写入到文件中,这种方法是通过获取文件信息,在网页上利用click事件,创建一个文件,然后将文件信息写入到文件中,然后保存。
<a name="download" (click)="downloadfile()"></a>
downloadfile(){
this.filecontent = "this is my file content";
this.url = "localhost:8000/home/home/file.txt";
let a = document.createElement('a');
a.href = "data:text/json;charset=utf-8,"+
this.filecontent;
a.download = "myfilename";
a.click();
}
3。 第三种方法和第一种类似,只是创建的是一个iframe。
<a name="download" (click)="downloadfile()"></a>
downloadfile(){
this.url = "localhost:8000/home/home/file.txt";
let elem = document.createElement('iframe');
elem.src = url;
elem.style.display = 'none';
document.body.appendChild(elem);
}
前两种方法详见:https://github.com/webPageDev/Demo
web端最简单的下载文件方式是采用html中a标签形式直接进行下载,只需要将文件的全路径赋值给href,同时给download属性赋予文件名即可。有些浏览器(IE8-11等)则在网页上直接打开,有时候还会是乱码。所以为了彻底解决这个,需要在服务器端想办法进行解决。
在spring框架下,通过href链接下载时,设置Servlet拦截相应的url,然后进入后台进行相应的输入。 示例代码如下:
public void fileOutputStream(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String filepath = req.getRequestURI();
int index = filepath.indexOf(Global.USERFILES_BASE_URL);
if(index >= 0) {
filepath = filepath.substring(index + Global.USERFILES_BASE_URL.length());
}
try {
filepath = UriUtils.decode(filepath, "UTF-8");
} catch (UnsupportedEncodingException e1) {
logger.error(String.format("解释文件路径失败,URL地址为%s", filepath), e1);
}
File file = new File(Global.getUserfilesBaseDir() +
Global.USERFILES_BASE_URL + filepath);
try {
resp.setContentType("application/x-msdownload; charset=utf-8");
resp.setHeader("Content-Disposition", "attachment;");
FileCopyUtils.copy(new FileInputStream(file), resp.getOutputStream());
return;
} catch (FileNotFoundException e) {
req.setAttribute("exception", new FileNotFoundException("请求的文件不存在"));
req.getRequestDispatcher("/WEB-INF/views/error/404.jsp").forward(req, resp);
}
}
关键代码:resp.setHeader(“Content-Disposition”, “attachment;”);这里指定输出是附件。这样的话,就明确的告诉浏览器这是在下载附件,从而解决了不同浏览器可能会出现直接打开文件甚至乱码问题。
对于tomcat而言,查看conf/web.xml,寻找所有的mime类型,如果存在你需要下载的文件的话,即不用进行修改,如果不存在的话,需要添加,然后重启服务器,给a标签赋值要下载文件的全路径即可(比如xls的文件就不用修改配置,而rar就需要配置,zip也不需要配置);注意,如果路径中包含中文的话,还需要稍微改动,否则可能会无法下载,需要在Server.xml文件中,在http端口设置处,需要加上编码,如下:
注意URIEncoding赋值为UTF-8,。因为对于get方式请求过来的编码,若文件路径中存在中文,则可能出现乱码。对于post请求过来的编码,可以用传统的request.setContent**方式进行配置。