fix(common) fileUpload fileDownload

approve-sys
bob 2 years ago
parent b70fdbba75
commit e1d6dfad78

@ -0,0 +1,80 @@
package com.ruoyi.web.controller.common;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysAttachment;
import com.ruoyi.system.service.ISysAttachmentService;
import com.ruoyi.web.core.config.AttachmentConfig;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Date;
/**
*
*
* @author ruoyi
*/
@Slf4j
@RestController
@RequestMapping("/common/attachment")
public class AttachmentController extends BaseController
{
@Autowired
private ISysAttachmentService attachmentService;
@Autowired
private TokenService tokenService;
@Autowired
private AttachmentConfig attachmentConfig;
/**
*
*/
@PostMapping("/upload")
public AjaxResult upload(@RequestParam("file") MultipartFile file) {
String yearMonth = LocalDate.now().toString("yyyy/MM");
String fileName = RandomUtil.randomString(12)+"."+FileUtil.getSuffix(file.getOriginalFilename());
String filePath = attachmentConfig.getPath() + FileUtil.FILE_SEPARATOR + yearMonth
+ FileUtil.FILE_SEPARATOR + fileName;
try {
FileUtil.writeFromStream(file.getInputStream(), filePath);
} catch (IOException e) {
log.error("upload::writeFromStream::fail", e);
throw new CustomException("文件保存失败,请重试!");
}
SysAttachment attachment = new SysAttachment();
attachment.setName(file.getOriginalFilename());
attachment.setType(FileUtil.getSuffix(file.getOriginalFilename()));
attachment.setContentType(file.getContentType());
attachment.setPath(filePath);
Date now = new Date();
attachment.setCreateTime(now);
attachment.setUpdateTime(now);
attachment.setCreateBy(tokenService.getLoginUserName(ServletUtils.getRequest()));
int result = attachmentService.insertSysAttachment(attachment);
if (result < 1) {
throw new CustomException("文件上传失败,请重试!");
}
return AjaxResult.success(MapUtil.of("id",attachment.getId()));
}
}

@ -0,0 +1,13 @@
package com.ruoyi.web.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "attachment")
public class AttachmentConfig {
private String path;
}

@ -48,9 +48,9 @@ spring:
servlet:
multipart:
# 单个文件大小
max-file-size: 10MB
max-file-size: 100MB
# 设置总上传的文件大小
max-request-size: 20MB
max-request-size: 200MB
# 服务模块
devtools:
restart:
@ -87,7 +87,7 @@ token:
secret: abcdefghijklmnopqrstuvwxyz
# 令牌有效期默认30分钟
expireTime: 30
# MyBatis配置
mybatis:
# 搜索指定包别名
@ -98,11 +98,11 @@ mybatis:
configLocation: classpath:mybatis/mybatis-config.xml
# PageHelper分页插件
pagehelper:
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
params: count=countSql
# Swagger配置
swagger:
@ -112,7 +112,7 @@ swagger:
pathMapping: /dev-api
# 防止XSS攻击
xss:
xss:
# 过滤开关
enabled: true
# 排除链接(多个用逗号分隔)
@ -126,3 +126,5 @@ flowable:
database-schema-update: false
# 关闭定时任务JOB
async-executor-activate: false
attachment:
path: /tmp

@ -1,33 +0,0 @@
package com.ruoyi.flowable.controller;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.flowable.domain.dto.FlowTaskDto;
import com.ruoyi.flowable.service.IFlowInstanceService;
import com.ruoyi.flowable.service.IFlowTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@Slf4j
@Api(tags = "工作流流程任务管理")
@RestController
@RequestMapping("/flowable/hisTask")
public class FlowHisTaskController {
@Autowired
private IFlowTaskService flowTaskService;
@ApiOperation(value = "我发起的流程", response = FlowTaskDto.class)
@GetMapping(value = "/myProcess")
public AjaxResult myProcess(@ApiParam(value = "当前页码", required = true) @RequestParam Integer pageNum,
@ApiParam(value = "每页条数", required = true) @RequestParam Integer pageSize) {
return flowTaskService.myProcess(pageNum, pageSize);
}
}

@ -0,0 +1,73 @@
package com.ruoyi.flowable.controller;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.SysAttachment;
import com.ruoyi.system.service.ISysAttachmentService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.Execution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/flowable/attachment")
public class SysAttachmentController {
@Autowired
private ISysAttachmentService attachmentService;
@Autowired
private RuntimeService runtimeService;
/**
*
*/
@GetMapping("/download")
public AjaxResult download(@RequestParam String processInstanceId, HttpServletResponse response) throws IOException {
if (StringUtils.isBlank(processInstanceId)) {
return AjaxResult.error("附件下载失败,参数无效");
}
Execution execution = runtimeService.createExecutionQuery().processInstanceId(processInstanceId).variableExists("attachmentIds").singleResult();
if (Objects.isNull(execution)) {
return AjaxResult.error("该流程无附件!");
}
Object attachmentIds = runtimeService.getVariable(execution.getId(), "attachmentIds");
if (StrUtil.isEmptyIfStr(attachmentIds)) {
return AjaxResult.error("该流程无附件!");
}
List<Long> ids = StrUtil.split(attachmentIds.toString(), ',', -1, true, Long::parseLong);
List<SysAttachment> attachments = ids.stream().map(e -> attachmentService.selectSysAttachmentById(e)).collect(Collectors.toList());
if (CollectionUtils.isEmpty(attachments)) {
return AjaxResult.error("下载失败,附件无效!");
}
List<String> fileNames = attachments.stream().map(e -> e.getName()).collect(Collectors.toList());
List<FileInputStream> fileInputStreams = attachments.stream().map(e -> e.getPath()).map(e -> {
try {
return new FileInputStream(e);
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
}).collect(Collectors.toList());
response.setHeader("content-type", "application/octet-stream");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setContentType("application/octet-stream");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=download.zip");
ZipUtil.zip(response.getOutputStream(), ArrayUtil.toArray(fileNames, String.class), ArrayUtil.toArray(fileInputStreams, FileInputStream.class));
return null;
}
}

@ -69,6 +69,26 @@ public class TokenService
}
return null;
}
/**
*
*
* @return
*/
public String getLoginUserName(HttpServletRequest request)
{
// 获取请求携带的令牌
String token = getToken(request);
if (StringUtils.isNotEmpty(token))
{
Claims claims = parseToken(token);
// 解析对应的权限以及用户信息
String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
String userKey = getTokenKey(uuid);
LoginUser user = redisCache.getCacheObject(userKey);
return user.getUsername();
}
return "";
}
/**
*

@ -0,0 +1,96 @@
package com.ruoyi.system.domain;
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;
/**
* sys_attachment
*
* @author ruoyi
* @date 2023-01-18
*/
public class SysAttachment extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** $column.columnComment */
private Long id;
/** 文件名 */
@Excel(name = "文件名")
private String name;
/** 文件类型 */
@Excel(name = "文件类型")
private String type;
/** 内容类型 */
@Excel(name = "内容类型")
private String contentType;
/** 文件路径 */
@Excel(name = "文件路径")
private String path;
public void setId(Long id)
{
this.id = id;
}
public Long getId()
{
return id;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setType(String type)
{
this.type = type;
}
public String getType()
{
return type;
}
public void setContentType(String contentType)
{
this.contentType = contentType;
}
public String getContentType()
{
return contentType;
}
public void setPath(String path)
{
this.path = path;
}
public String getPath()
{
return path;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("name", getName())
.append("type", getType())
.append("contentType", getContentType())
.append("path", getPath())
.append("createTime", getCreateTime())
.append("updateTime", getUpdateTime())
.append("createBy", getCreateBy())
.toString();
}
}

@ -0,0 +1,62 @@
package com.ruoyi.system.mapper;
import com.ruoyi.system.domain.SysAttachment;
import java.util.List;
/**
* Mapper
*
* @author ruoyi
* @date 2023-01-18
*/
public interface SysAttachmentMapper
{
/**
*
*
* @param id ID
* @return
*/
public SysAttachment selectSysAttachmentById(Long id);
/**
*
*
* @param sysAttachment
* @return
*/
public List<SysAttachment> selectSysAttachmentList(SysAttachment sysAttachment);
/**
*
*
* @param sysAttachment
* @return
*/
public int insertSysAttachment(SysAttachment sysAttachment);
/**
*
*
* @param sysAttachment
* @return
*/
public int updateSysAttachment(SysAttachment sysAttachment);
/**
*
*
* @param id ID
* @return
*/
public int deleteSysAttachmentById(Long id);
/**
*
*
* @param ids ID
* @return
*/
public int deleteSysAttachmentByIds(Long[] ids);
}

@ -0,0 +1,62 @@
package com.ruoyi.system.service;
import com.ruoyi.system.domain.SysAttachment;
import java.util.List;
/**
* Service
*
* @author ruoyi
* @date 2023-01-18
*/
public interface ISysAttachmentService
{
/**
*
*
* @param id ID
* @return
*/
public SysAttachment selectSysAttachmentById(Long id);
/**
*
*
* @param sysAttachment
* @return
*/
public List<SysAttachment> selectSysAttachmentList(SysAttachment sysAttachment);
/**
*
*
* @param sysAttachment
* @return
*/
public int insertSysAttachment(SysAttachment sysAttachment);
/**
*
*
* @param sysAttachment
* @return
*/
public int updateSysAttachment(SysAttachment sysAttachment);
/**
*
*
* @param ids ID
* @return
*/
public int deleteSysAttachmentByIds(Long[] ids);
/**
*
*
* @param id ID
* @return
*/
public int deleteSysAttachmentById(Long id);
}

@ -0,0 +1,97 @@
package com.ruoyi.system.service.impl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.SysAttachment;
import com.ruoyi.system.mapper.SysAttachmentMapper;
import com.ruoyi.system.service.ISysAttachmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Service
*
* @author ruoyi
* @date 2023-01-18
*/
@Slf4j
@Service
public class SysAttachmentServiceImpl implements ISysAttachmentService
{
@Autowired
private SysAttachmentMapper sysAttachmentMapper;
/**
*
*
* @param id ID
* @return
*/
@Override
public SysAttachment selectSysAttachmentById(Long id)
{
return sysAttachmentMapper.selectSysAttachmentById(id);
}
/**
*
*
* @param sysAttachment
* @return
*/
@Override
public List<SysAttachment> selectSysAttachmentList(SysAttachment sysAttachment)
{
return sysAttachmentMapper.selectSysAttachmentList(sysAttachment);
}
/**
*
*
* @param sysAttachment
* @return
*/
@Override
public int insertSysAttachment(SysAttachment sysAttachment)
{
sysAttachment.setCreateTime(DateUtils.getNowDate());
return sysAttachmentMapper.insertSysAttachment(sysAttachment);
}
/**
*
*
* @param sysAttachment
* @return
*/
@Override
public int updateSysAttachment(SysAttachment sysAttachment)
{
sysAttachment.setUpdateTime(DateUtils.getNowDate());
return sysAttachmentMapper.updateSysAttachment(sysAttachment);
}
/**
*
*
* @param ids ID
* @return
*/
@Override
public int deleteSysAttachmentByIds(Long[] ids)
{
return sysAttachmentMapper.deleteSysAttachmentByIds(ids);
}
/**
*
*
* @param id ID
* @return
*/
@Override
public int deleteSysAttachmentById(Long id)
{
return sysAttachmentMapper.deleteSysAttachmentById(id);
}
}

@ -0,0 +1,83 @@
<?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.SysAttachmentMapper">
<resultMap type="SysAttachment" id="SysAttachmentResult">
<result property="id" column="id" />
<result property="name" column="name" />
<result property="type" column="type" />
<result property="contentType" column="content_type" />
<result property="path" column="path" />
<result property="createTime" column="create_time" />
<result property="updateTime" column="update_time" />
<result property="createBy" column="create_by" />
</resultMap>
<sql id="selectSysAttachmentVo">
select id, name, type, content_type, path, create_time, update_time, create_by from sys_attachment
</sql>
<select id="selectSysAttachmentList" parameterType="SysAttachment" resultMap="SysAttachmentResult">
<include refid="selectSysAttachmentVo"/>
<where>
<if test="name != null and name != ''"> and name like concat('%', #{name}, '%')</if>
<if test="type != null and type != ''"> and type = #{type}</if>
<if test="contentType != null and contentType != ''"> and content_type = #{contentType}</if>
<if test="path != null and path != ''"> and path = #{path}</if>
</where>
</select>
<select id="selectSysAttachmentById" parameterType="Long" resultMap="SysAttachmentResult">
<include refid="selectSysAttachmentVo"/>
where id = #{id}
</select>
<insert id="insertSysAttachment" parameterType="SysAttachment" useGeneratedKeys="true" keyProperty="id">
insert into sys_attachment
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null and name != ''">name,</if>
<if test="type != null and type != ''">type,</if>
<if test="contentType != null and contentType != ''">content_type,</if>
<if test="path != null and path != ''">path,</if>
<if test="createTime != null">create_time,</if>
<if test="updateTime != null">update_time,</if>
<if test="createBy != null and createBy != ''">create_by,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="name != null and name != ''">#{name},</if>
<if test="type != null and type != ''">#{type},</if>
<if test="contentType != null and contentType != ''">#{contentType},</if>
<if test="path != null and path != ''">#{path},</if>
<if test="createTime != null">#{createTime},</if>
<if test="updateTime != null">#{updateTime},</if>
<if test="createBy != null and createBy != ''">#{createBy},</if>
</trim>
</insert>
<update id="updateSysAttachment" parameterType="SysAttachment">
update sys_attachment
<trim prefix="SET" suffixOverrides=",">
<if test="name != null and name != ''">name = #{name},</if>
<if test="type != null and type != ''">type = #{type},</if>
<if test="contentType != null and contentType != ''">content_type = #{contentType},</if>
<if test="path != null and path != ''">path = #{path},</if>
<if test="createTime != null">create_time = #{createTime},</if>
<if test="updateTime != null">update_time = #{updateTime},</if>
<if test="createBy != null and createBy != ''">create_by = #{createBy},</if>
</trim>
where id = #{id}
</update>
<delete id="deleteSysAttachmentById" parameterType="Long">
delete from sys_attachment where id = #{id}
</delete>
<delete id="deleteSysAttachmentByIds" parameterType="String">
delete from sys_attachment where id in
<foreach item="id" collection="array" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
</mapper>
Loading…
Cancel
Save