下载文件

This commit is contained in:
zhanglipeng 2021-01-29 12:55:18 +08:00
parent b18f274121
commit 85900682b8
4 changed files with 95 additions and 55 deletions

View File

@ -1,40 +1,67 @@
import axios from 'axios' import axios from 'axios'
import { getToken } from '@/utils/auth' import { getToken } from '@/utils/auth'
const mimeMap = { const mimeMap = {
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
zip: 'application/zip' zip: 'application/zip'
} }
const baseUrl = process.env.VUE_APP_BASE_API const baseUrl = process.env.VUE_APP_BASE_API
export function downLoadZip(str, filename) { export function downLoadZip(str, filename) {
var url = baseUrl + str var url = baseUrl + str
axios({ axios({
method: 'get', method: 'get',
url: url, url: url,
responseType: 'blob', responseType: 'blob',
headers: { 'Authorization': 'Bearer ' + getToken() } headers: { 'Authorization': 'Bearer ' + getToken() }
}).then(res => { }).then(res => {
resolveBlob(res, mimeMap.zip) resolveBlob(res, mimeMap.zip)
}) })
} }
/** export function downLoadUrl(str, item) {
* 解析blob响应内容并下载 var url = baseUrl + str
* @param {*} res blob响应内容 axios({
* @param {String} mimeType MIME类型 method: 'get',
*/ url: url,
export function resolveBlob(res, mimeType) { params: { name: item.fileurl },
const aLink = document.createElement('a') responseType: 'blob',
var blob = new Blob([res.data], { type: mimeType }) headers: { 'Authorization': 'Bearer ' + getToken() },
// //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名; }).then(res => {
var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*') console.log(res);
var contentDisposition = decodeURI(res.headers['content-disposition']) downloadFileFun(res, item)
var result = patt.exec(contentDisposition) })
var fileName = result[1] }
fileName = fileName.replace(/\"/g, '')
aLink.href = URL.createObjectURL(blob) export function downloadFileFun(data, item) {
aLink.setAttribute('download', fileName) // 设置下载文件名称 if (!data) {
document.body.appendChild(aLink) return
aLink.click() }
document.body.appendChild(aLink) let url = window.URL.createObjectURL(new Blob([data]))
} let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', item.name)
document.body.appendChild(link)
link.click()
}
/**
* 解析blob响应内容并下载
* @param {*} res blob响应内容
* @param {String} mimeType MIME类型
*/
export function resolveBlob(res, mimeType) {
const aLink = document.createElement('a')
var blob = new Blob([res.data], { type: mimeType })
// //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
var contentDisposition = decodeURI(res.headers['content-disposition'])
var result = patt.exec(contentDisposition)
var fileName = result[1]
fileName = fileName.replace(/\"/g, '')
aLink.href = URL.createObjectURL(blob)
aLink.setAttribute('download', fileName) // 设置下载文件名称
document.body.appendChild(aLink)
aLink.click()
document.body.appendChild(aLink)
}

View File

@ -12,13 +12,18 @@
</el-card> </el-card>
</el-col> </el-col>
</el-row> --> </el-row> -->
<ul class="infinite-list" v-infinite-scroll="load" style="overflow:auto"> <ul class="infinite-list" v-infinite-scroll="load" style="overflow: auto">
<li v-for="(ele, i) in filesList" :key="i" class="flex align-center justify-between infinite-list-item"> <li
v-for="(ele, i) in filesList"
:key="i"
class="flex align-center justify-between infinite-list-item"
>
<div class="left"> <div class="left">
<span>{{i + 1}}.</span> <span>{{ i + 1 }}.</span>
<i class="el-icon-document icon"></i>{{ele.name}} <i class="el-icon-document icon"></i>{{ ele.name }}
</div> </div>
<a class="right" :href="apiurl + ele.fileurl">下载</a> <!-- <a class="right" :href="apiurl + ele.fileurl">下载</a> -->
<a class="right" @click="down(ele)">下载</a>
</li> </li>
</ul> </ul>
</div> </div>
@ -26,6 +31,7 @@
<script> <script>
import { listFiles, getFiles } from "@/api/benyi/files"; import { listFiles, getFiles } from "@/api/benyi/files";
import { downLoadUrl } from "@/utils/zipdownload";
export default { export default {
name: "childFiles", name: "childFiles",
@ -43,8 +49,8 @@ export default {
filetype: undefined, filetype: undefined,
type: "1", // type: "1", //
fileurl: undefined, fileurl: undefined,
createuserid: undefined createuserid: undefined,
} },
}; };
}, },
created() { created() {
@ -54,15 +60,16 @@ export default {
/** 查询文件管理列表 */ /** 查询文件管理列表 */
getList() { getList() {
this.loading = true; this.loading = true;
listFiles(this.queryParams).then(response => { listFiles(this.queryParams).then((response) => {
this.filesList = response.rows; this.filesList = response.rows;
this.loading = false; this.loading = false;
}); });
}, },
load() { load() {},
down(row) {
} downLoadUrl('/common/download/resource',row);
} },
},
}; };
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>

View File

@ -94,9 +94,9 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
"/**/*.css", "/**/*.css",
"/**/*.js" "/**/*.js"
).permitAll() ).permitAll()
.antMatchers("/profile/**").anonymous() // .antMatchers("/profile/**").anonymous()
.antMatchers("/common/download**").anonymous() // .antMatchers("/common/download**").anonymous()
.antMatchers("/common/download/resource**").anonymous() // .antMatchers("/common/download/resource**").anonymous()
.antMatchers("/swagger-ui.html").anonymous() .antMatchers("/swagger-ui.html").anonymous()
.antMatchers("/swagger-resources/**").anonymous() .antMatchers("/swagger-resources/**").anonymous()
.antMatchers("/webjars/**").anonymous() .antMatchers("/webjars/**").anonymous()

View File

@ -140,6 +140,10 @@ public class CommonController {
return ajax; return ajax;
} }
/**
*获取七牛资源地址
*@param URL 上传的资源名称
*/
public String privateDownloadUrl(String URL) { public String privateDownloadUrl(String URL) {
Auth auth = Auth.create(constantQiniu.getAccessKey(), constantQiniu.getSecretKey()); Auth auth = Auth.create(constantQiniu.getAccessKey(), constantQiniu.getSecretKey());
@ -156,8 +160,10 @@ public class CommonController {
public void resourceDownload(String name, HttpServletRequest request, HttpServletResponse response) throws Exception { public void resourceDownload(String name, HttpServletRequest request, HttpServletResponse response) throws Exception {
// 本地资源路径 // 本地资源路径
String localPath = RuoYiConfig.getProfile(); String localPath = RuoYiConfig.getProfile();
// System.out.println("localPath:"+localPath);
// 数据库资源地址 // 数据库资源地址
String downloadPath = localPath + StringUtils.substringAfter(name, Constants.RESOURCE_PREFIX); String downloadPath = localPath + StringUtils.substringAfter(name, Constants.RESOURCE_PREFIX);
// System.out.println("downloadPath:"+downloadPath);
// 下载名称 // 下载名称
String downloadName = StringUtils.substringAfterLast(downloadPath, "/"); String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
response.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");