js 文件下载,当前页下载,新标签下载____后端返回 GET/POST 文件流,下载文件...

  • ajax
  • /**
     * Created by kjf on 2019-03-25.
     *
     * axios.request(config)
       axios.get(url[, config])
       axios.post(url[, data[, config]])
       axios.delete(url[, config])
       axios.head(url[, config])
       axios.options(url[, config])
       axios.put(url[, data[, config]])
       axios.patch(url[, data[, config]])
     */
    import axios from 'axios';
    
    export default function (url, data = {}, method = 'GET', params, headers) {
        return new Promise((resolve, reject) => {
            let promise = null;
            if (method === 'GET') {
                promise = axios.get(url, {params: data, headers});
            } else if (method === 'POST') {
                promise = axios.post(url, data, {params: params, headers});
            }
            promise
                .then(response => resolve(response))
                .catch(err => {
                    // console.log("/src/axios/ajax.js----error: "+err)
                    reject(err);
                });
        });
    }

1. 直接用 Ajax 发 POST/GET 请求

错误的方式:

  • export const requestDownloadLabFile = (id) => { // 下载附件
        const url = preFixed + '/lab/myExperimentOperator/download/' + id;
        return ajax(url, {}, 'GET', {}, {'labAuth': 'http://localhost:7000'});
    };

正确的方式:(缺点: 必须要知道 文件名.类型,意味着后端必须给到 这样的一个字段)

  • export const requestDownloadLabFile = (id) => { // 下载附件
        const url = preFixed + '/lab/myExperimentOperator/download/' + id;
    
        ajax(url, {}, 'GET', {}, {'labAuth': 'http://localhost:7000'}).then(res=> {
                const content = res.data;
                const blob = new Blob([content]);
                const fileName = 'fileName.type';
                if ('download' in document.createElement('a')) { // 非IE下载
                    const elink = document.createElement('a');
                    elink.download = fileName;
                    elink.style.display = 'none';
                    elink.href = URL.createObjectURL(blob);
                    document.body.appendChild(elink);
                    elink.click();
                    URL.revokeObjectURL(elink.href); // 释放URL 对象
                    document.body.removeChild(elink);
                } else { // IE10+下载
                    navigator.msSaveBlob(blob, fileName);
                }
        });
        return 0;
    }

2. window.open 此类方法,兼容性不好

  • export const requestDownloadLabFile = (id) => { // 下载附件
        const url = preFixed + '/lab/myExperimentOperator/download/' + id;
    
        window.open(url, '_blank'); // 新打开窗口
    };

3. form 当前页下载: (当 链接失效 时,影响当前页, 但是可以接受)____推荐使用

  • diyDownload
  • export const diyDownload = (url, data, method = 'GET') => {
        const body = document.getElementsByTagName('body')[0];
        const form = document.createElement('form');
        form.method = method;
        form.action = url;
        for (let key in data) {
            let param = document.createElement('input');
            param.type = 'hidden';
            param.name = key;
            param.value = data[key];
            form.appendChild(param);
        }
        body.appendChild(form);
        form.submit();
        body.removeChild(form);
    };
  • export const requestDownloadLabFile = (id) => { // 下载附件
        const url = preFixed + '/lab/myExperimentOperator/download/' + id;
        diyDownload(url, {}, 'GET');
    };

4. iframe 标签下载: (当 链接失效 时,不会影响当前页)

  • export const requestDownloadLabFile = (id) => { // 下载附件
        const url = preFixed + '/lab/myExperimentOperator/download/' + id;
    
        try {
            let elemIF = document.createElement('iframe');
            elemIF.src = url;
            elemIF.style.display = 'none';
            document.body.appendChild(elemIF);
        } catch (e) {
            myConsole('下载异常!');
        }
    };

 

转载于:https://www.cnblogs.com/tianxiaxuange/p/10983284.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
前端代码(HTML、JavaScript、JSP): ```html <!-- 文件列表展示 --> <table> <thead> <tr> <th>文件名</th> <th>文件大小</th> <th>上传时间</th> <th>操作</th> </tr> </thead> <tbody id="fileList"></tbody> </table> <!-- 分 --> <div class="pagination"> <ul> <li><a href="javascript:void(0);" onclick="getPageData(1)">首</a></li> <li><a href="javascript:void(0);" onclick="getPageData(currentPage-1)">上一</a></li> <li><a href="javascript:void(0);" onclick="getPageData(currentPage+1)">下一</a></li> <li><a href="javascript:void(0);" onclick="getPageData(totalPages)">末</a></li> <li><a href="javascript:void(0);">共<span id="totalPages"></span></a></li> <li><a href="javascript:void(0);">当前第<span id="currentPage"></span></a></li> </ul> </div> <!-- 上传文件 --> <form id="uploadForm" enctype="multipart/form-data"> <input type="file" name="file" /> <button type="submit" onclick="uploadFile()">上传</button> </form> <!-- 删除文件 --> <button onclick="deleteFile()">删除</button> <!-- 下载文件 --> <a id="downloadLink" href="#" download></a> <script> var currentPage = 1; // 当前页码 var totalPages = 0; // 总数 // 获取文件列表数据 function getPageData(page) { currentPage = page; $.ajax({ url: "/file/list", type: "GET", data: { pageNum: currentPage }, success: function(result) { // 处理返回的数据 $("#fileList").html(""); $.each(result.records, function(index, item) { var tr = "<tr>" + "<td>" + item.fileName + "</td>" + "<td>" + item.fileSize + "</td>" + "<td>" + item.uploadTime + "</td>" + "<td><input type='checkbox' name='fileId' value='" + item.id + "' /></td>" + "</tr>"; $("#fileList").append(tr); }); // 更信息 totalPages = result.pages; $("#totalPages").text(totalPages); $("#currentPage").text(currentPage); } }); } // 上传文件 function uploadFile() { var formData = new FormData($("#uploadForm")[0]); $.ajax({ url: "/file/upload", type: "POST", data: formData, contentType: false, processData: false, success: function() { alert("上传成功!"); getPageData(currentPage); }, error: function() { alert("上传失败!"); } }); } // 删除文件 function deleteFile() { var fileIds = $("input[name='fileId']:checked").map(function() { return $(this).val(); }).get(); if (fileIds.length == 0) { alert("请选择要删除的文件!"); return; } $.ajax({ url: "/file/delete", type: "POST", data: { fileIds: fileIds.join(",") }, success: function() { alert("删除成功!"); getPageData(currentPage); }, error: function() { alert("删除失败!"); } }); } // 下载文件 function downloadFile(fileId) { $("#downloadLink").attr("href", "/file/download?fileId=" + fileId); $("#downloadLink").get(0).click(); } // 面加载完成时获取第一数据 $(function() { getPageData(1); }); </script> ``` 后端代码(Java): ```java @Controller @RequestMapping("/file") public class FileController { @Autowired private FileSystem fileSystem; // 分展示文件列表 @GetMapping("/list") @ResponseBody public ResultVO<PageInfo<FileVO>> listFiles(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) { List<FileVO> fileVOList = new ArrayList<>(); try { RemoteIterator<LocatedFileStatus> fileStatusList = fileSystem.listFiles(new Path("/"), true); while (fileStatusList.hasNext()) { LocatedFileStatus fileStatus = fileStatusList.next(); FileVO fileVO = new FileVO(); fileVO.setId(UUID.randomUUID().toString()); fileVO.setFileName(fileStatus.getPath().getName()); long fileSize = fileStatus.getLen(); if (fileSize < 1024) { fileVO.setFileSize(fileSize + " B"); } else if (fileSize < 1048576) { fileVO.setFileSize(fileSize / 1024 + " KB"); } else { fileVO.setFileSize(fileSize / 1048576 + " MB"); } fileVO.setUploadTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(fileStatus.getModificationTime()))); fileVOList.add(fileVO); } } catch (IOException e) { e.printStackTrace(); } PageInfo<FileVO> pageInfo = new PageInfo<>(fileVOList, pageNum, pageSize); return ResultVO.success(pageInfo); } // 上传文件 @PostMapping("/upload") @ResponseBody public ResultVO<?> uploadFile(@RequestParam("file") MultipartFile file) { try { FSDataOutputStream outputStream = fileSystem.create(new Path("/" + file.getOriginalFilename())); IOUtils.copyBytes(file.getInputStream(), outputStream, 4096, true); return ResultVO.success(); } catch (IOException e) { e.printStackTrace(); return ResultVO.error("上传文件失败!"); } } // 删除文件 @PostMapping("/delete") @ResponseBody public ResultVO<?> deleteFile(@RequestParam("fileIds") String fileIds) { String[] fileIdArray = fileIds.split(","); for (String fileId : fileIdArray) { try { fileSystem.delete(new Path("/" + fileId), false); } catch (IOException e) { e.printStackTrace(); return ResultVO.error("删除文件失败!"); } } return ResultVO.success(); } // 下载文件 @GetMapping("/download") public void downloadFile(@RequestParam("fileId") String fileId, HttpServletResponse response) { try { FSDataInputStream inputStream = fileSystem.open(new Path("/" + fileId)); response.setHeader("Content-Disposition", "attachment; filename=" + fileId); IOUtils.copyBytes(inputStream, response.getOutputStream(), 4096, true); } catch (IOException e) { e.printStackTrace(); } } } ``` 其中,`FileVO` 类用于封装文件信息,`ResultVO` 类用于统一接口返回格式,`PageInfo` 类用于封装分信息。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值