在系统开发中,文件的上传和下载是一个常用的功能点。本着好记性不如烂笔头的原则,我们从这边记录一下

系统环境

RuoYi-Vue 3.4.0
element-ui vue2

前端文件

后端处理

/**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = ProcessConsultationConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = configService.selectConfigByKey("profile_key") + fileName;
            Map<String,Object> ajax = new HashMap<>();
            ajax.put("fileName", fileName);
            ajax.put("reallyName", file.getOriginalFilename());
            ajax.put("url", url);
            return AjaxResult.success(ajax);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

通用下载

 /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StrUtil.format("资源文件({})非法,不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = ProcessConsultationConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StrUtil.subAfter(resource, Constants.RESOURCE_PREFIX,false);
            // 下载名称
            String downloadName = StrUtil.subAfter(downloadPath, "/",true);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            File file = new File(downloadPath);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeToStream(file, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

标签: none

相关阅读

  • 测试信息
  • 拼多多2023年度财报分析
  • 2023年最后一个工作日
  • 2023山东社会责任企业(企业家)” 推选活动结果
  • 测试信息
  • 测试信息
  • 测试信息