RuoYi framework implements file download implementation

This article only modifies the download file function of the ruoyi template.


Front-end
Notes: Don’t use ajax to pass parameters. You can use location.href. Using ajax to call the Controller will not start the download. The file pops up, but the file will be downloaded normally, and the console will not report an error. The downloaded file will find the binary file data in the response of the latest request in the network in the browser
The filenames all start with /profile/upload

Front-end code implementation:

Js implementation:

function downLoads(evidenceUrl,evidenceName) {
            window.location.href=ctx +"common/download/resource?resource="+ evidenceUrl + "&name=" + evidenceName;
        }

Backend code implementation:

    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, String name, HttpServletRequest request, HttpServletResponse response) {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法,不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            if (!name.equals("") && name != null) {
                FileUtils.setAttachmentResponseHeader(response, name);
            } else {
                FileUtils.setAttachmentResponseHeader(response, downloadName);
            }
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("下载文件失败", e);

        }
    }

Guess you like

Origin blog.csdn.net/cyl101816/article/details/123894605