附件上传下载

commonController.java

package com.ruoyi.web.controller.common;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.Sysfiles;
import com.ruoyi.system.service.ISysfileService;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;

import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@RestController
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Resource
    private ISysfileService sysfileService;

    @Autowired
    private TokenService tokenService;

    String datePath = "yyyy"+File.separator+"MM"+File.separator+"dd";

    private SimpleDateFormat format = new SimpleDateFormat(datePath);


    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file,int maxSize,HttpServletRequest request)
    {
        //定义返回
        AjaxResult ajax = null;
        //获取当前日期
        Date now = new Date();
        try
        {
            // 上传文件路径
            //构造日期路径进一步隔离文件防止重复
            String filePath = RuoYiConfig.getUploadPath() + File.separator + format.format(now);
            //获取文件信息
            String fileFullName = file.getOriginalFilename();
            String fileType = file.getContentType();
            long fileSize =  file.getSize();
            //300是因为数据库设置最大长度300
            if (fileFullName.length() > 300){
                ajax = AjaxResult.error("文件名称超过限制!");
                return ajax;
            }
            if (fileSize > maxSize * 1024 * 1024 ){
                ajax = AjaxResult.error("文件大小超过限制!");
                return ajax;
            }
            //构造文件对象保存
            Sysfiles sysfile = new Sysfiles();
            //文件名称
            sysfile.setFilename(fileFullName);
            //文件类型
            sysfile.setFiletype(fileType);
            //文件大小
            sysfile.setFilesize(fileSize);
            //文件路径
            sysfile.setFilepath(filePath);
            //文件上传者
            String userName = "未知用户";
            if (tokenService.getLoginUser(request) != null){
                //获取token中携带的用户信息,取自redis
                userName = tokenService.getLoginUser(request).getUsername();
            }
            sysfile.setOper(userName);
            //文件上传时间
            sysfile.setOpertime(now);
            //保存至文件表,获取保存id
            sysfileService.insertSysfile(sysfile);
            // 上传并返回新文件名称
            Long fid = sysfile.getFid();
            String fileName = FileUploadUtils.uploadByFid(filePath, file,fid);
            if (fileName != null && fileName != ""){
                //上传成功构造返回
                ajax = AjaxResult.success("文件上传成功!",sysfile);
            }else {
                ajax = AjaxResult.error("文件上传失败!");
            }
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 根据文件ID读取文件流
     */
    @GetMapping("/common/getFile/{fileid}")
    public void outputFile(@PathVariable("fileid")Long FID, HttpServletRequest request, HttpServletResponse response){
        //声明流
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //获取文件信息
            Sysfiles file = sysfileService.selectSysfileById(FID);
            //设置响应参数
            if (file != null){
                if (file.getFilepath() != null && !"".equals(file.getFilepath())){

                    //设置响应参数
                    response.setContentType(file.getFiletype());
                    response.setCharacterEncoding("UTF-8");
                    response.setHeader("Content-disposition", "attachment; filename=" + encodeFileName(request,file.getFilename()));
                    response.setHeader("Content-Length", file.getFilesize().toString());
                    //获取文件后缀名,拼接
                    String fileName = FID.toString()+"."+FilenameUtils.getExtension(file.getFilename());
                    File realFile = new File(file.getFilepath(), fileName);
                    bis = new BufferedInputStream(new FileInputStream(realFile));
                    bos = new BufferedOutputStream(response.getOutputStream());
                    byte[] buff = new byte[2048];
                    int bytesRead;
                    while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                        bos.write(buff, 0, bytesRead);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException var29) {
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException var28) {
                }
            }
        }
    }

    /**
     * 根据不同浏览器请求,文件名重新编码
     */
    public static String encodeFileName(HttpServletRequest request, String fileName) {
        String nfileName = null;

        try {
            if (request == null) {
                return URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
            }

            String userAgent = request.getHeader("User-Agent");
            if (userAgent != null) {
                userAgent = userAgent.toLowerCase();
                if (userAgent.indexOf("msie") != -1) {
                    nfileName = URLEncoder.encode(fileName, "UTF-8");
                } else if (userAgent.indexOf("safari") != -1) {
                    nfileName = URLEncoder.encode(fileName, "UTF-8");
                    //nfileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                } else {
                    nfileName = URLEncoder.encode(fileName, "UTF-8");
                }
            } else {
                nfileName = URLEncoder.encode(fileName, "UTF-8");
            }

            if (nfileName == null) {
                String ext = null;
                int dot = fileName.lastIndexOf(".");
                if (dot != -1 && dot != fileName.length() - 1) {
                    ext = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                }

                nfileName = (new Date()).getTime() + "";
                if (ext != null) {
                    nfileName = nfileName + ext;
                }
            }
        } catch (UnsupportedEncodingException var6) {

        }

        return nfileName.replace("+", "%20");
    }



    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        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);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
}

FileUpLoadUtils.java

package com.ruoyi.common.utils.file;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.file.FileNameLengthLimitExceededException;
import com.ruoyi.common.exception.file.FileSizeLimitExceededException;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;

/**
 * 文件上传工具类
 *
 * @author ruoyi
 */
public class FileUploadUtils
{
    /**
     * 默认大小 50M
     */
    public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;

    /**
     * 默认的文件名最大长度 100
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;

    /**
     * 默认上传的地址
     */
    private static String defaultBaseDir = RuoYiConfig.getProfile();

    public static void setDefaultBaseDir(String defaultBaseDir)
    {
        FileUploadUtils.defaultBaseDir = defaultBaseDir;
    }

    public static String getDefaultBaseDir()
    {
        return defaultBaseDir;
    }

    /**
     * 以默认配置进行文件上传
     *
     * @param file 上传的文件
     * @return 文件名称
     * @throws Exception
     */
    public static final String upload(MultipartFile file) throws IOException
    {
        try
        {
            return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        }
        catch (Exception e)
        {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file 上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static final String upload(String baseDir, MultipartFile file) throws IOException
    {
        try
        {
            return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        }
        catch (Exception e)
        {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 文件上传
     *
     * @param baseDir 相对应用的基目录
     * @param file 上传的文件
     * @param allowedExtension 上传文件类型
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException 如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException 比如读写文件出错时
     * @throws InvalidExtensionException 文件校验异常
     */
    public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
            InvalidExtensionException
    {
        int fileNamelength = file.getOriginalFilename().length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
        {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }

        assertAllowed(file, allowedExtension);

        String fileName = extractFilename(file);

        File desc = getAbsoluteFile(baseDir, fileName);
        file.transferTo(desc);
        String pathFileName = getPathFileName(baseDir, fileName);
        return pathFileName;
    }

    /**
     * 根据文件ID上传文件
     *
     * @param baseDir 相对应用的基目录
     * @param file 上传的文件
     * @param
     * @return 返回上传成功的文件名
     * @throws IOException 比如读写文件出错时
     * @throws InvalidExtensionException 文件校验异常
     */
    public static final String uploadByFid(String baseDir, MultipartFile file,Long Fid)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException
    {
        String fileName = extractFilenameByFid(file,Fid);

        File desc = getAbsoluteFile(baseDir, fileName);
        file.transferTo(desc);
        String pathFileName = getPathFileName(baseDir, fileName);
        return pathFileName;
    }

    /**
     * 编码文件名
     */
    public static final String extractFilenameByFid(MultipartFile file,Long Fid)
    {
        String fileName = "";
        String extension = getExtension(file);
        //重做文件名,将文件名修改为 fid.xxx
        fileName =  Fid + "." + extension;
        return fileName;
    }


    /**
     * 编码文件名
     */
    public static final String extractFilename(MultipartFile file)
    {
        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        fileName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension;
        return fileName;
    }

    private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
    {
        File desc = new File(uploadDir + File.separator + fileName);

        if (!desc.getParentFile().exists())
        {
            desc.getParentFile().mkdirs();
        }
        if (!desc.exists())
        {
            desc.createNewFile();
        }
        return desc;
    }

    private static final String getPathFileName(String uploadDir, String fileName) throws IOException
    {
        int dirLastIndex = RuoYiConfig.getProfile().length() + 1;
        String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
        String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
        return pathFileName;
    }

    /**
     * 文件大小校验
     *
     * @param file 上传的文件
     * @return
     * @throws FileSizeLimitExceededException 如果超出最大大小
     * @throws InvalidExtensionException
     */
    public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
            throws FileSizeLimitExceededException, InvalidExtensionException
    {
        long size = file.getSize();
        if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE)
        {
            throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
        }

        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension))
        {
            if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION)
            {
                throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
                        fileName);
            }
            else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION)
            {
                throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
                        fileName);
            }
            else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION)
            {
                throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
                        fileName);
            }
            else
            {
                throw new InvalidExtensionException(allowedExtension, extension, fileName);
            }
        }

    }

    /**
     * 判断MIME类型是否是允许的MIME类型
     *
     * @param extension
     * @param allowedExtension
     * @return
     */
    public static final boolean isAllowedExtension(String extension, String[] allowedExtension)
    {
        for (String str : allowedExtension)
        {
            if (str.equalsIgnoreCase(extension))
            {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension(MultipartFile file)
    {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension))
        {
            extension = MimeTypeUtils.getExtension(file.getContentType());
        }
        return extension;
    }
}

SysFileController.java

package com.ruoyi.web.controller.system;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.Sysfiles;
import com.ruoyi.system.service.ISysfileService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * 文件信息控制器
 *
 * @author wangqq
 */
@RestController
@RequestMapping("/system/file")
public class SysFileController {


    @Resource
    private ISysfileService sysfileService;


    @GetMapping("/listByIds/{fileIds}")
    public AjaxResult getFileInfos(@PathVariable("fileIds") String fileIds){
        AjaxResult backResult = null;
        List<Sysfiles> fileList = sysfileService.selectByIds(fileIds);
        if (fileList.size() > 0 ){
            //文件获取成功
            backResult = AjaxResult.success("获取成功",fileList);
        }else {
            backResult = AjaxResult.error("获取失败");
        }
        return backResult;
    }


}

Sysfiles.java

package com.ruoyi.system.domain;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import java.util.Date;

/**
 * 文件对象 sysfile
 *
 * @author ruoyi
 * @date 2021-05-26
 */
public class Sysfiles extends BaseEntity
{
    private static final long serialVersionUID = 1L;

    /** 文件的唯一标识符 */
    private Long fid;

    /** 文件名称 */
    @Excel(name = "文件名称")
    private String filename;

    /** 文件类型 */
    @Excel(name = "文件类型")
    private String filetype;

    /** 文件大小 */
    @Excel(name = "文件大小")
    private Long filesize;

    /** 文件保存路径 */
    @Excel(name = "文件保存路径")
    private String filepath;

    /** 文件内容身份证 */
    @Excel(name = "文件内容身份证")
    private String filemd5;

    /** 文件存储类型 */
    @Excel(name = "文件存储类型")
    private String savetype;

    /** 操作者 */
    @Excel(name = "操作者")
    private String oper;

    /** 操作时间 */
    @JsonFormat(pattern = "yyyy-MM-dd")
    @Excel(name = "操作时间", width = 30, dateFormat = "yyyy-MM-dd")
    private Date opertime;

    /** 操作机器IP */
    @Excel(name = "操作机器IP")
    private String operip;

    /** 文件PFID */
    @Excel(name = "文件PFID")
    private String pid;

    /** 文件下载次数 */
    @Excel(name = "文件下载次数")
    private Long dloadtimes;

    public void setFid(Long fid)
    {
        this.fid = fid;
    }

    public Long getFid()
    {
        return fid;
    }
    public void setFilename(String filename)
    {
        this.filename = filename;
    }

    public String getFilename()
    {
        return filename;
    }
    public void setFiletype(String filetype)
    {
        this.filetype = filetype;
    }

    public String getFiletype()
    {
        return filetype;
    }
    public void setFilesize(Long filesize)
    {
        this.filesize = filesize;
    }

    public Long getFilesize()
    {
        return filesize;
    }
    public void setFilepath(String filepath)
    {
        this.filepath = filepath;
    }

    public String getFilepath()
    {
        return filepath;
    }
    public void setFilemd5(String filemd5)
    {
        this.filemd5 = filemd5;
    }

    public String getFilemd5()
    {
        return filemd5;
    }
    public void setSavetype(String savetype)
    {
        this.savetype = savetype;
    }

    public String getSavetype()
    {
        return savetype;
    }
    public void setOper(String oper)
    {
        this.oper = oper;
    }

    public String getOper()
    {
        return oper;
    }
    public void setOpertime(Date opertime)
    {
        this.opertime = opertime;
    }

    public Date getOpertime()
    {
        return opertime;
    }
    public void setOperip(String operip)
    {
        this.operip = operip;
    }

    public String getOperip()
    {
        return operip;
    }
    public void setPid(String pid)
    {
        this.pid = pid;
    }

    public String getPid()
    {
        return pid;
    }
    public void setDloadtimes(Long dloadtimes)
    {
        this.dloadtimes = dloadtimes;
    }

    public Long getDloadtimes()
    {
        return dloadtimes;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
            .append("fid", getFid())
            .append("filename", getFilename())
            .append("filetype", getFiletype())
            .append("filesize", getFilesize())
            .append("filepath", getFilepath())
            .append("filemd5", getFilemd5())
            .append("savetype", getSavetype())
            .append("oper", getOper())
            .append("opertime", getOpertime())
            .append("operip", getOperip())
            .append("pid", getPid())
            .append("dloadtimes", getDloadtimes())
            .toString();
    }
}

SysfileMapper.java

package com.ruoyi.system.mapper;

import com.ruoyi.system.domain.Sysfiles;

import java.util.List;

/**
 * 【文件信息】Mapper接口
 *
 * @author ruoyi
 * @date 2021-05-26
 */
public interface SysfileMapper
{
    /**
     * 查询【文件信息】
     *
     * @param fid 【文件信息】ID
     * @return 【文件信息】
     */
    public Sysfiles selectSysfileById(Long fid);

    /**
     * 查询【文件信息】列表
     *
     * @param sysfile 【文件信息】
     * @return 【文件信息】集合
     */
    public List<Sysfiles> selectSysfileList(Sysfiles sysfile);

    /**
     * 新增【文件信息】
     *
     * @param sysfile 【文件信息】
     * @return 结果
     */
    public int insertSysfile(Sysfiles sysfile);

    /**
     * 修改【文件信息】
     *
     * @param sysfile 【文件信息】
     * @return 结果
     */
    public int updateSysfile(Sysfiles sysfile);

    /**
     * 删除【文件信息】
     *
     * @param fid 【文件信息】ID
     * @return 结果
     */
    public int deleteSysfileById(Long fid);

    /**
     * 批量删除【文件信息】
     *
     * @param fids 需要删除的数据ID
     * @return 结果
     */
    public int deleteSysfileByIds(Long[] fids);


    /**
     * 批量查询文件信息【文件信息】
     *
     * @param fids 需要查询的文件id数组
     * @return 结果
     */
    List<Sysfiles> selectByIds(List<Long> fids);

}

SysfileServiceImpl.java

package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.Sysfiles;
import com.ruoyi.system.mapper.SysfileMapper;
import com.ruoyi.system.service.ISysfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 【文件信息】Service业务层处理
 *
 * @author ruoyi
 * @date 2021-05-26
 */
@Service
public class SysfileServiceImpl implements ISysfileService
{
    @Autowired
    private SysfileMapper sysfileMapper;

    /**
     * 查询【文件信息】
     *
     * @param fid 【文件信息】ID
     * @return 【文件信息】
     */
    @Override
    public Sysfiles selectSysfileById(Long fid)
    {
        return sysfileMapper.selectSysfileById(fid);
    }

    /**
     * 查询【文件信息】列表
     *
     * @param sysfile 【文件信息】
     * @return 【文件信息】
     */
    @Override
    public List<Sysfiles> selectSysfileList(Sysfiles sysfile)
    {
        return sysfileMapper.selectSysfileList(sysfile);
    }

    /**
     * 新增【文件信息】
     *
     * @param sysfile 【文件信息】
     * @return 结果
     */
    @Override
    public int insertSysfile(Sysfiles sysfile)
    {
        return sysfileMapper.insertSysfile(sysfile);
    }

    /**
     * 修改【文件信息】
     *
     * @param sysfile 【文件信息】
     * @return 结果
     */
    @Override
    public int updateSysfile(Sysfiles sysfile)
    {
        return sysfileMapper.updateSysfile(sysfile);
    }

    /**
     * 批量删除【文件信息】
     *
     * @param fids 需要删除的【文件信息】ID
     * @return 结果
     */
    @Override
    public int deleteSysfileByIds(Long[] fids)
    {
        return sysfileMapper.deleteSysfileByIds(fids);
    }

    /**
     * 删除【文件信息】信息
     *
     * @param fid 【文件信息】ID
     * @return 结果
     */
    @Override
    public int deleteSysfileById(Long fid)
    {
        return sysfileMapper.deleteSysfileById(fid);
    }

    @Override
    public List<Sysfiles> selectByIds(String fileIds) {
        String[] files = fileIds.split(",");
        List<Long> ids = new ArrayList();
        for (String fid : files){
            ids.add(Long.parseLong(fid));
        }
        return sysfileMapper.selectByIds(ids);
    }

}

ISysfileService.java

package com.ruoyi.system.service;

import com.ruoyi.system.domain.Sysfiles;

import java.util.List;

/**
 * 【文件信息】Service接口
 *
 * @author ruoyi
 * @date 2021-05-26
 */
public interface ISysfileService
{
    /**
     * 查询【文件信息】
     *
     * @param fid 【文件信息】ID
     * @return 【文件信息】
     */
    public Sysfiles selectSysfileById(Long fid);

    /**
     * 查询【文件信息】列表
     *
     * @param sysfile 【文件信息】
     * @return 【文件信息】集合
     */
    public List<Sysfiles> selectSysfileList(Sysfiles sysfile);

    /**
     * 新增【文件信息】
     *
     * @param sysfile 【文件信息】
     * @return 结果
     */
    public int insertSysfile(Sysfiles sysfile);

    /**
     * 修改【文件信息】
     *
     * @param sysfile 【文件信息】
     * @return 结果
     */
    public int updateSysfile(Sysfiles sysfile);

    /**
     * 批量删除【文件信息】
     *
     * @param fids 需要删除的【文件信息】ID
     * @return 结果
     */
    public int deleteSysfileByIds(Long[] fids);

    /**
     * 删除【文件信息】信息
     *
     * @param fid 【文件信息】ID
     * @return 结果
     */
    public int deleteSysfileById(Long fid);

    /**
     * 批量查询文件信息【文件信息】
     *
     * @param fileIds 需要查询的文件id拼接字符串
     * @return 结果
     */
    List<Sysfiles> selectByIds(String fileIds);



}

SysfileMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ruoyi.system.mapper.SysfileMapper">

    <resultMap type="Sysfiles" id="SysfileResult">
        <result property="fid"    column="FID"    />
        <result property="filename"    column="FILENAME"    />
        <result property="filetype"    column="FILETYPE"    />
        <result property="filesize"    column="FILESIZE"    />
        <result property="filepath"    column="FILEPATH"    />
        <result property="filemd5"    column="FILEMD5"    />
        <result property="savetype"    column="SAVETYPE"    />
        <result property="oper"    column="OPER"    />
        <result property="opertime"    column="OPERTIME"    />
        <result property="operip"    column="OPERIP"    />
        <result property="pid"    column="PID"    />
        <result property="dloadtimes"    column="DLOADTIMES"    />
    </resultMap>

    <sql id="selectSysfileVo">
        select FID, FILENAME, FILETYPE, FILESIZE, FILEPATH, FILEMD5, SAVETYPE, OPER, OPERTIME, OPERIP, PID, DLOADTIMES from sysfile
    </sql>

    <select id="selectSysfileList" parameterType="com.ruoyi.system.domain.Sysfiles" resultMap="SysfileResult">
        <include refid="selectSysfileVo"/>
        <where>
            <if test="filename != null  and filename != ''"> and FILENAME like concat('%', #{filename}, '%')</if>
            <if test="filetype != null  and filetype != ''"> and FILETYPE = #{filetype}</if>
            <if test="filesize != null "> and FILESIZE = #{filesize}</if>
            <if test="filepath != null  and filepath != ''"> and FILEPATH = #{filepath}</if>
            <if test="filemd5 != null  and filemd5 != ''"> and FILEMD5 = #{filemd5}</if>
            <if test="savetype != null  and savetype != ''"> and SAVETYPE = #{savetype}</if>
            <if test="oper != null  and oper != ''"> and OPER = #{oper}</if>
            <if test="opertime != null "> and OPERTIME = #{opertime}</if>
            <if test="operip != null  and operip != ''"> and OPERIP = #{operip}</if>
            <if test="pid != null  and pid != ''"> and PID = #{pid}</if>
            <if test="dloadtimes != null "> and DLOADTIMES = #{dloadtimes}</if>
        </where>
    </select>

    <select id="selectSysfileById" parameterType="Long" resultMap="SysfileResult">
        <include refid="selectSysfileVo"/>
        where FID = #{fid}
    </select>

    <insert id="insertSysfile" parameterType="Sysfile" useGeneratedKeys="true" keyProperty="fid">
        insert into sysfile
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="filename != null">FILENAME,</if>
            <if test="filetype != null">FILETYPE,</if>
            <if test="filesize != null">FILESIZE,</if>
            <if test="filepath != null">FILEPATH,</if>
            <if test="filemd5 != null">FILEMD5,</if>
            <if test="savetype != null">SAVETYPE,</if>
            <if test="oper != null">OPER,</if>
            <if test="opertime != null">OPERTIME,</if>
            <if test="operip != null">OPERIP,</if>
            <if test="pid != null">PID,</if>
            <if test="dloadtimes != null">DLOADTIMES,</if>
         </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="filename != null">#{filename},</if>
            <if test="filetype != null">#{filetype},</if>
            <if test="filesize != null">#{filesize},</if>
            <if test="filepath != null">#{filepath},</if>
            <if test="filemd5 != null">#{filemd5},</if>
            <if test="savetype != null">#{savetype},</if>
            <if test="oper != null">#{oper},</if>
            <if test="opertime != null">#{opertime},</if>
            <if test="operip != null">#{operip},</if>
            <if test="pid != null">#{pid},</if>
            <if test="dloadtimes != null">#{dloadtimes},</if>
         </trim>
    </insert>

    <update id="updateSysfile" parameterType="Sysfile">
        update sysfile
        <trim prefix="SET" suffixOverrides=",">
            <if test="filename != null">FILENAME = #{filename},</if>
            <if test="filetype != null">FILETYPE = #{filetype},</if>
            <if test="filesize != null">FILESIZE = #{filesize},</if>
            <if test="filepath != null">FILEPATH = #{filepath},</if>
            <if test="filemd5 != null">FILEMD5 = #{filemd5},</if>
            <if test="savetype != null">SAVETYPE = #{savetype},</if>
            <if test="oper != null">OPER = #{oper},</if>
            <if test="opertime != null">OPERTIME = #{opertime},</if>
            <if test="operip != null">OPERIP = #{operip},</if>
            <if test="pid != null">PID = #{pid},</if>
            <if test="dloadtimes != null">DLOADTIMES = #{dloadtimes},</if>
        </trim>
        where FID = #{fid}
    </update>

    <delete id="deleteSysfileById" parameterType="Long">
        delete from sysfile where FID = #{fid}
    </delete>

    <delete id="deleteSysfileByIds" parameterType="String">
        delete from sysfile where FID in
        <foreach item="fid" collection="array" open="(" separator="," close=")">
            #{fid}
        </foreach>
    </delete>

    <select id="selectByIds" resultMap="SysfileResult" >
--         select
        <include refid="selectSysfileVo"/>
--         from sysfile
        where  fid in
        <foreach collection="list" item="fid" index="index" open="(" close=")" separator=",">
            #{fid}
        </foreach>
    </select>


</mapper>

uploadfile.js

import request from '@/utils/request'
import { praseStrEmpty } from "@/utils/ruoyi";

// 文件上传
export function uploadData(data) {
  return request({
    url: '/common/upload',
    method: 'post',
    data: data
  })
}
//获取单个文件文件流数据
export function getFile(data) {
  return request({
    url: '/common/getFile/' + data,
    method: 'get',
    responseType:'blob'
  })
}
//获取文件列表
export function getFileList(data) {
  return request({
    url: '/system/file/listByIds/' + data,
    method: 'get'
  })
}

file_check.png

file_del.png

UploadInput\index.vue

<template>
  <div>
    <el-row>
      <el-upload
        class="upload-demo"
        ref="upload"
        :action="uploadFileUrl"
        :headers="{ 'Authorization': token }"
        :data="{'maxSize':fileSize }"
        :on-change="handleChange"
        :on-exceed="handleExceed"
        :on-success="handleUploadSuccess"
        :on-error="submitErr"
        :auto-upload="false"
        :show-file-list="false"
        :multiple="true"
        :limit="limit"
        v-if="show"
      >
        <el-input slot="trigger" v-model="upload.fileName" readonly
                  style="float: left;width:80%;margin-right:5%;"></el-input>
        <img src="../../assets/images/file_choose.png" title="选取文件" alt="选取文件" slot="trigger">
        <img src="../../assets/images/file_upload.png" title="上传到服务器" alt="上传到服务器" @click="submitUpload"
             style="cursor: pointer;">
        <div class="el-upload__tip" slot="tip" v-if="showTip">
          请上传
          <template v-if="upload.fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
          <template v-if="upload.fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
          的文件
        </div>
      </el-upload>
      <ul class="list_ul" v-show="ulDiasbled">
        <li class="list_li" v-for="(ite,index) in List" v-on:click.stop="showFile(ite)">
          <span class="li_name">{{ ite.filename }}</span>
          <i :class="elIcon" v-on:click.stop="fileRemove(index,ite.fid)"></i>
        </li>
      </ul>
    </el-row>
    <el-dialog title="查看文件" :visible.sync="open" width="1000px" append-to-body :closeOnClickModal=false>
      <div class="file_div">
        <img :src="imgFile"/>
        <div class="imgname" v-on:click.stop="downloadFile(imgFile,imgName)">{{ imgName }}</div>
        <a></a>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import pdf from 'vue-pdf'
import {getFile, getFileList} from "@/api/system/uploadfile";
import {getToken} from '@/utils/auth'

export default {
  components: {pdf},
  props: {
    fileType: {
      type: Array,
      default: () => ["doc", "xls", "ppt", "txt", "pdf"],
    },
    limit: {
      type: Number,
      default: () => 1,
    },
    showLimit: {
      type: Number,
      default: () => 1,
    },
    fileSize: {
      type: Number,
      default: () => 30,
    },
    //文件上传组件状态,add:新增,update:修改,view:查看
    uploadType: {
      type: String
    },
    fileIds: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传服务器地址(生产环境)
      // uploadFileUrl: "http://218.94.131.134:28088/common/upload", // 上传服务器地址(正式环境)
      token: "Bearer " + getToken(),
      upload: {
        // 文件名称
        fileName: '',
        // 大小限制(MB)
        fileSize: this.fileSize,
        // 文件类型, 例如['png', 'jpg', 'jpeg']
        fileType: this.fileType,
        //文件id
        id: ''
      },
      // 是否显示提示
      isShowTip: true,
      //校验结果
      isLegal: true,
      fileNameArr: [],
      List: [],
      ulDiasbled: false,
      imgHidden: false,
      imgFile: '',
      //文件上传组件是否显示,查看状态下隐藏
      show: true,
      //文件列表图标
      elIcon: 'el-icon-circle-close',
      //查看dialog
      // 是否显示弹出层
      open: false,
      imgName: '',
    };
  },
  created() {
  },
  computed: {
    showTip() {
      return this.isShowTip && (this.upload.fileType || this.upload.fileSize);
    }
  },
  watch: {
    uploadType(val) {
      //监听uploadType
      this.uploadType = val
      this.fileStatus();
    },
    fileIds(val) {
      //监听fileIds
      this.fileIds = val
      this.getFilsIds();
    }
  },
  mounted() {
    this.fileStatus();//文件状态
    this.getFilsIds();//文件数组
  },
  methods: {
    getFilsIds() {
      if (this.uploadType !== "add") {
        if (this.fileIds.length != 0 && this.fileIds != "") {
          //文件数组不为空加载文件列表
          getFileList(this.fileIds.join(',')).then(res => {
            this.List = res.data
            this.ulDiasbled = true;
          })
        }
      }
    },
    //判断文件上传的状态
    fileStatus() {
      //新增
      if (this.uploadType === "add") {
        this.show = true;
      } else if (this.uploadType === "upload") {
        this.show = true;
        this.elIcon = "el-icon-circle-close";
      } else {
        this.show = false;
        this.elIcon = ""
      }
    },
    //父组件重置文件上传
    fileReset() {

      //清空文本框内值
      this.fileNameArr = [];
      this.upload.fileName="";

      //清空显示列表
      this.List = [];

      //清空控件内文件信息
      if (this.show == true) {
         this.$refs.upload.clearFiles();
      }

    },
    // 文件上传失败
    submitErr(err) {
      this.$message.error("上传失败, 请重试");
    },
    //文件状态改变
    handleChange(file, fileList) {
      //清空文件名数组重新赋值未上传成功的文件名
      if (this.HandleLegal(file)) {
        this.fileNameArr = [];
        fileList.forEach(file => {
          if (file.status == "ready"){
            this.fileNameArr.push(file.name);
          }
        })
        this.upload.fileName = this.fileNameArr.join(",");
      }
    },
    // 校验
    HandleLegal(file) {
      // 校检文件类型
      if (this.upload.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.upload.fileType.some((type) => {
          if (file.raw.type.indexOf(type) > -1) {
            this.isLegal = true;
            return true;
          }
          if (fileExtension && fileExtension.indexOf(type) > -1) {
            this.isLegal = true;
            return true;
          }
          this.isLegal = false;
          return false;

        });
        if (this.fileType.includes(fileExtension)) {
          this.upload.fileName = file.name
        } else {
          this.$refs.upload.handleRemove(file)
        }
        if (!isTypeOk) {
          this.$message.error(`文件格式不正确, 请上传${this.upload.fileType.join("/")}格式文件!`);
          this.isLegal = false;
          return false;
        }
      }
      // 校检文件大小
      if (this.upload.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.upload.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.upload.fileSize} MB!`);
          this.isLegal = false;
          return false;
        }
      }
      this.isLegal = true;
      return true;
    },
    // 文件超出个数限制时
    handleExceed(files, fileList) {

      this.$message.warning(`当前限制上传 ${this.showLimit} 个文件 ! `);

    },
    submitUpload() {

      this.$refs.upload.submit();

    },
    // 上传成功回调
    handleUploadSuccess(res, file, fileList) {

      //清空文本框的值
      this.upload.fileName = "";
      if (200 === res.code) {
        //重新赋值文本框列表
        this.List = [];
        fileList.forEach(file => {
          //仅获取上传成功的
          if (file.status == "success") {
            this.List.push(file.response.data);
          }
        })
        this.ulDiasbled = true
        this.fileIds.push("" + res.data.fid)
        this.$message.success(file.name + "   上传成功 !");
      }
    },
    //文件删除
    fileRemove(index, fid) {
      this.List.splice(index, 1)
      let xb = this.fileIds.indexOf("" + fid);
      this.fileIds.splice(xb, 1);
      console.log(this.fileIds)
      if(this.fileIds.length=0){
        this.fileIds = null;
      }
    },
    //文件列表移除文件
    handleRemove(file, fileList) {
      //console.log(file, fileList);
    },
    //点击文件列表中已上传的文件
    handlePreview(file) {
      //console.log(file);
    },
    showFile(ite) {
      getFile(ite.fid).then(res => {
          let blob = new Blob([res]);
          let objectUrl = window.URL.createObjectURL(blob);
          this.imgFile = objectUrl;
          this.imgName = ite.filename
          this.open = true;
      }).catch(err => {
        console.log(err)
      })

      //新增
      // if (this.uploadType === "add") {
      //   getFile(this.fileID).then(res => {
      //     let blob = new Blob([res]);
      //     let objectUrl = window.URL.createObjectURL(blob);
      //     this.imgFile = objectUrl;
      //     this.imgName = ite.filename
      //     this.open = true;
      //   }).catch(err => {
      //     console.log(err)
      //   })
      // } else {
      //   //查看
      //   getFile(ite.fid).then(res => {
      //     let blob = new Blob([res]);
      //     let objectUrl = window.URL.createObjectURL(blob);
      //     this.imgFile = objectUrl;
      //     this.imgName = ite.filename
      //     this.open = true;
      //   }).catch(err => {
      //     console.log(err)
      //   })
      // }
    },
    downloadFile(content, filename) {
      let a = document.createElement('a')
      a.href = content
      a.download = filename
      a.click()
    }
  }
}
</script>
<style>
.el-message {
  top: 100px !important;
  z-index: 99999 !important;
}

.el-upload {
  text-align: left;
  width: 90%;
}
</style>
<style scoped>
.list_ul {
  color: #909399;
  font-size: 14px;
  padding: 0;
  list-style: none;
  margin-left: 0;
}

.list_li {
  height: 24px;
  line-height: 24px;
  margin-bottom: 3px;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.li_name {
  width: 94%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
  color: blue;
  text-decoration: underline;
}

.file_div {
  z-index: 1;
  width: 100%;
  margin: 0 auto;
  text-align: center;
}

/deep/ .el-dialog .el-dialog__body {
  margin-top: 70px;
  height: 500px !important;
}

.imgname {
  color: blue;
  cursor: pointer;
  margin-left: 10px;
}
/deep/.el-icon-circle-check:before{
  content: url("../../assets/images/file_check.png");
  width: 18px;
  height: 18px;
}
/deep/.el-icon-circle-close:before{
  content: url("../../assets/images/file_del.png");
  width: 18px;
  height: 18px;
}
</style>

相关数据表看sql建立即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值