上传下载

首先创建一张上传文件的表,例如:

  1. drop table if exists sys_file_info;
  2. create table sys_file_info (
  3. file_id int(11) not null auto_increment comment '文件id',
  4. file_name varchar(50) default '' comment '文件名称',
  5. file_path varchar(255) default '' comment '文件路径',
  6. primary key (file_id)
  7. ) engine=innodb auto_increment=1 default charset=utf8 comment = '文件信息表';

上传实现流程

1、代码生成sys_file_info表相关代码并复制到对应目录。
2、参考示例修改代码。

<input id="filePath" name="filePath" class="form-control" type="file">

1

function submitHandler() {
    if ($.validate.form()) {
        uploadFile();
    }
}
function uploadFile() {
    var formData = new FormData();
    if ($('#filePath')[0].files[0] == null) {
        $.modal.alertWarning("请先选择文件路径");
        return false;
    }
    formData.append('fileName', $("#fileName").val());
    formData.append('file', $('#filePath')[0].files[0]);
    $.ajax({
        url: prefix + "/add",
        type: 'post',
        cache: false,
        data: formData,
        processData: false,
        contentType: false,
        dataType: "json",
        success: function(result) {
            $.operate.successCallback(result);
        }
    });
}

3、在FileInfoController添加对应上传方法

@PostMapping("/add")
@ResponseBody
public AjaxResult addSave(@RequestParam("file") MultipartFile file, FileInfo fileInfo) throws IOException
{
    // 上传文件路径
    String filePath = RuoYiConfig.getUploadPath();
    // 上传并返回新文件名称
    String fileName = FileUploadUtils.upload(filePath, file);
    fileInfo.setFilePath(fileName);
    return toAjax(fileInfoService.insertFileInfo(fileInfo));
}

4、上传成功后需要预览可以对该属性格式化处理

{
    field : 'filePath', 
    title: '文件预览',
    formatter: function(value, row, index) {
        return $.table.imageView(value);
    }
},

如需对文件格式控制,设置application.yml中的multipart属性

# 文件上传
servlet:
   multipart:
     # 单个文件大小
     max-file-size:  10MB
     # 设置总上传的文件大小
     max-request-size:  20MB

注意:如果只是单纯的上传一张图片没有其他参数可以使用通用方法 /common/upload
请求处理方法 com.ruoyi.web.controller.common.CommonController

下载实现流程

1、参考示例代码。

function downloadFile(value){
    window.location.href = ctx + "common/download/resource?resource=" + value;
}

2、参考Controller下载方法

/**
 * 本地资源通用下载
 */
@GetMapping("/common/download/resource")
public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
        throws Exception
{
    // 本地资源路径
    String localPath = Global.getProfile();
    // 数据库资源地址
    String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
    // 下载名称
    String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
    response.setCharacterEncoding("utf-8");
    response.setContentType("multipart/form-data");
    response.setHeader("Content-Disposition",
            "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
    FileUtils.writeBytes(downloadPath, response.getOutputStream());
}