1.后端接口
- @GetMapping(value = "/download")
- public void download(HttpServletResponse res, HttpServletResponse response) throws Exception {
- String fileName = "科协页面详细说明.docx";
- String path = "C://Users/hanku/Desktop/"+fileName;
- // 把二进制流放入到响应体中
- File file = new File(path);
- if (file.exists()) {
- byte[] data = null;
- FileInputStream input = new FileInputStream(file);
- data = new byte[input.available()];
- input.read(data);
- // 根据文件类型,设置文件Content-Type
- String fileType = fileName.substring(fileName.lastIndexOf(".")).toUpperCase();
- // 设置Content-Type头
- switch (fileType) {
- case ".JPG":
- response.setContentType("image/jpeg");
- break;
- case ".JPEG":
- response.setContentType("image/jpeg");
- break;
- case ".PNG":
- response.setContentType("image/png");
- break;
- case ".PDF":
- response.setContentType("application/pdf");
- break;
- case ".DOC":
- response.setContentType("application/msword");
- break;
- case ".DOCX":
- case ".docx":
- response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
- break;
- default:
- response.setContentType("application/json");
- }
- response.getOutputStream().write(data);
- input.close();
- }
- }
2.vue前端
vue项目要先下载插件哦
npm i docx-preview@0.1.4
npm i jszip
这里面有两种预览效果,一种是一层层找相应的docx文件,另一种是指定目录和文件名打开
参考资料:https://zhuanlan.zhihu.com/p/437059185
- <template>
- <div class="my-component" ref="preview">
- <!-- //https://blog.csdn.net/weixin_52103939/article/details/122447620 -->
- <input type="file" @change="preview" ref="file" />
- <button @click="goPreview">di</button>
- <div ref="preview"></div>
- </div>
- </template>
- <script>
- const docx = require("docx-preview");
- window.JSZip = require("jszip");
- export default {
- methods: {
- preview(e) {
- docx.renderAsync(this.$refs.file.files[0], this.$refs.preview); // 渲染到页面预览
- },
- // 预览
- goPreview() {
- //参考资料:https://zhuanlan.zhihu.com/p/437059185
- // axios({
- // method: "get",
- // responseType: "blob", // 因为是流文件,所以要指定blob类型或者arraybuffer
- // url: "localhost:13000/download", // 自己的服务器,提供的一个word下载文件接口
- // }).then(({ data }) => {
- // debugger
- // console.log(data); // 后端返回的是流文件
- // docx.renderAsync(data, this.$refs.file); // 渲染到页面
- // });
-
- this.$http({ method: "get", url: "/download", responseType: "blob" })
- .then((response) => {
- console.log(response);
- docx.renderAsync(response.data, this.$refs.preview); // 渲染到页面(着重注意
- this.$refs.preview要和<div ref="preview"></div>保持一致)
- })
- .catch(function (error) {});
- },
- },
- };
- </script>
- <style lang="less" scoped>
- .my-component {
- width: 100%;
- height: 90vh;
- border: 1px solid #000;
- }
- </style>