vue+Java 文件下载
背景
算是第一次,前后端自己琢磨文件下载了。直接上代码吧。
前端代码
<template>
<div>
<!-- 列表 -->
<el-row>
<el-table :data="docs" ref="docs" style="width: 100%" stripe @sort-change="sort" v-loading="loading">
<el-table-column prop="docFileName" :label="$t('gts.doc.fileName')" sortable align="center" min-width="10%"></el-table-column>
<el-table-column prop="id" align="center" min-width="20%">
<template slot-scope="scope">
<a @click="download(scope.$index, scope.row)">
<i class="fas fa-download" style="color:#409EFF"></i>
</a>
</template>
</el-table-column>
</el-table>
<div class="pagination">
<el-pagination
@size-change="handleSizeChange"
@current-change="handlePageChange"
:current-page="page"
:page-size="limit"
:total="total"
:page-sizes="[10, 20, 50, 100]"
layout="total, sizes, prev, pager, next, jumper"
:background="true"
></el-pagination>
</div>
</el-row>
</div>
</template>
<script>
import { list } from "@/api/gts/document";
import { selectDict } from "@/api/common";
import { cst } from "@/utils/constants";
export default {
name: "GtsDocument",
data() {
return {
limitNum: 1,
fileList: [],
docs: [],
loading: false,
page: 1,
limit: 10,
total: 0,
};
},
created: function() {
this.search();
},
methods: {
search() {
list(this.page, this.limit, this.$route.query.gtsId).then(v => {
if ("ok" == v.data.msg) {
this.docs = v.data.rows;
this.total = v.data.total;
}
});
},
// 下载事件
download(index, row) {
var path = row.docPath + row.docFileName;
// path例如:D:\home\upload\da975319173641669a6fca212ffd272e\夕阳.jpg
window.open("http://localhost:8080/api/documents/download?path=" + encodeURI(path));
},
sort() {},
handlePageChange(i) {
this.page = i;
this.search();
},
handleSizeChange(i) {
this.limit = i;
this.search();
},
}
};
</script>
后台controller
/**
* <p>Description: 下载</p>
*
* @param path 路径
* @param response
*/
@GetMapping("/api/documents/download")
public void download(String path, HttpServletResponse response) {
try {
// path: 欲下载的文件的路径
File file = new File(path);
// 获取文件名 - 设置字符集 String downloadFileName = new String(file.getName().getBytes(StandardCharsets.UTF_8), "iso-8859-1");
// 以流的形式下载文件
InputStream fis;
fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
页面效果
