js+html+java文件下载(1)

上篇文章说的是文件的预览,这里来说一下文件的下载,出入职场,种种不足欢迎指出,由于xml文件的格式比较特殊,因为和html存在冲突,所以在这里说明一下我用的是这个标签,因为 标签之间的内容不会被当作文档内容解析,而会被用等宽字体直接呈现。

@RequestMapping(value = "/previewFile", method = RequestMethod.GET)
    public String previewFile(String key, String fileFormat) {
        String url = getPath(key);
        String aimPath = url.replace(fileFormat, ".html");
        String encode = "";
        String fileContent = "";
        try {
            encode = EncodingDetect.getJavaEncode(url);
            fileContent = FileUtils.readFileToString(new File(url), encode);
        } catch (Exception e) {
            logger.warn("文件转换异常");
        }
        File newfile = new File(aimPath);
        String str = "<html><head></head><title>" + newfile.getName() + "</title><xmp style='margin-left: 5px;'>" + fileContent + "</xmp></html>";
        return str;
    }

本身是下载+预览的功能,这里主要介绍下载

<body>
<button onclick="downLoad()" id="btn">下载</button>
    <iframe id="mainframe" style="float: left;width:100%;height:96%;" frameborder="0"  scrolling="auto"></iframe>
</body>
function downLoad() {
        window.location.href = baseURL + "cms/systemModuleFileCollectNonCommon/downLoadFile?path=" + encodeURIComponent(filePath)+"&&ip="+ip;
    }

后端下载的java接口

//保存文件
    @RequestMapping("downLoadFile")
    public void downLoadFile(String ip, String path, HttpServletRequest request, HttpServletResponse response) {
        try {
            path = getPath(path);
            File file = new File(path);
            String name = file.getName();
            String ori = name.substring(0, name.lastIndexOf("."));
            String rev = name.substring(name.lastIndexOf("."), name.length());

            FileInputStream inputStream = null;
            inputStream = new FileInputStream(file);
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(ori + "(" + ip + ")" + rev, "UTF-8"));
            OutputStream out = response.getOutputStream();
            ///向out中写入流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            response.flushBuffer();
        } catch (IOException ex) {
            logger.error(ex.getMessage());
        }
    }

到这里下载的功能就完成了,欢迎指正不足

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 后端实现文件下载 在Spring Boot中,我们可以使用以下代码实现文件下载: ```java @GetMapping("/download") public ResponseEntity<Resource> downloadFile() throws IOException { Resource resource = new UrlResource("file:/path/to/file"); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\""); return ResponseEntity.ok().headers(headers).contentLength(resource.contentLength()).contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource); } ``` 其中,`UrlResource`是Spring提供的获取文件资源的类,`HttpHeaders.CONTENT_DISPOSITION`设置文件下载方式为附件,`MediaType.APPLICATION_OCTET_STREAM`指定文件类型为二进制流。 2. 前端实现文件下载 在Vue中,我们可以使用Element UI中的`el-button`组件来实现文件下载: ```html <el-button type="primary" icon="el-icon-download" @click="downloadFile">下载文件</el-button> ``` 在Vue组件中,我们需要定义`downloadFile`方法来实现文件下载: ```javascript downloadFile() { window.location.href = '/download'; } ``` 其中,`window.location.href`将页面重定向到下载链接,即后端实现的文件下载接口。 需要注意的是,如果需要传递参数给后端,可以使用axios或者fetch来发送GET或POST请求,将参数传递给后端,再在后端实现文件下载。具体实现方法可以参考以下代码: ```javascript downloadFile() { axios.get('/download', { params: { filename: 'example.txt' }, responseType: 'blob' }).then(response => { const blob = new Blob([response.data], {type: 'application/octet-stream'}) const url = window.URL.createObjectURL(blob) const link = document.createElement('a') link.href = url link.download = 'example.txt' link.click() window.URL.revokeObjectURL(url) }) } ``` 在这个例子中,我们使用了axios来发送GET请求,`params`中传递了参数filename,`responseType`设置返回类型为二进制流。在请求成功后,我们将返回的数据转换为Blob对象,通过URL.createObjectURL方法生成下载链接,然后创建一个a标签并设置download属性,模拟点击a标签来下载文件。最后使用URL.revokeObjectURL方法释放资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值