Spring+ Angularjs 文件下载功能

最近在做一个附件下载的功能,需要使用Angularjs下载文件,贴点代码,希望有用;

1.Spring后端代码

这里上传的文件是存放在某个文件夹目录下的,直接通过将file转换成输入流,然后copy到输出流中即可

FileInputStream fileInputStream = FileUtils.openInputStream(file);
        IOUtils.copy(fileInputStream, outputStream);
        outputStream.close();
        outputStream.flush();

在controller中添加输出的类型

response.setContentType("application/octet-stream");

2.Angularjs前端代码

Angularjs直接是不可以通过http请求的方式下载文件,需要做点额外的处理,这里其实是构造了一个链接,然后执行链接的点击,去请求文件的下载;

$http({
                method: 'POST',
                url: 'api/file/downLoad',
                data: {fileName: name},
                responseType: 'arraybuffer'
            }).success(function (data, status, headers) {
                headers = headers();
                var contentType = headers['content-type'];
                var linkElement = document.createElement('a');
                try {
                    var blob = new Blob([data], {type: contentType});
                    var url = window.URL.createObjectURL(blob);
                    linkElement.setAttribute('href', url);
                    linkElement.setAttribute("download", name);
                    var clickEvent = new MouseEvent("click", {
                        "view": window,
                        "bubbles": true,
                        "cancelable": false
                    });
                    linkElement.dispatchEvent(clickEvent);
                } catch (ex) {
                    console.log(ex);
                }
            }).error(function (data) {
                console.log(data);
            });
总结:后端就是将文件内容放到输出流中,前端请求接收到之后构造链接,url对应文件内容,模拟点击去请求下载;

猜你喜欢

转载自blog.csdn.net/xiaoguangtouqiang/article/details/80105717