修改图片上传方式为Sftp 导出没有调通

hyx_2024-10-12_xgfPerson
shanao 2024-09-09 18:05:42 +08:00
parent 5197b10d4e
commit c6ea9844ca
5 changed files with 65 additions and 79 deletions

View File

@ -140,7 +140,7 @@ public class AccidentRecordsController extends BaseController {
* @return * @return
*/ */
@RequestMapping("/import/photos") @RequestMapping("/import/photos")
public Map<String, Object> importPhotos(@RequestParam MultipartFile file) { public Map<String, Object> importPhotos(@RequestParam("file") MultipartFile file) {
if (file == null || file.isEmpty()) { if (file == null || file.isEmpty()) {
throw new RuntimeException("文件不能为空"); throw new RuntimeException("文件不能为空");
} }
@ -153,11 +153,12 @@ public class AccidentRecordsController extends BaseController {
/** /**
* *
* *
* @param path * @param request
* @return * @return
*/ */
@RequestMapping("/delete/photos/{path}") @RequestMapping("/delete/photos")
public Map<String, Object> deletePhotos(@PathVariable("path") String path) { public Map<String, Object> deletePhotos(HttpServletRequest request) {
String path = new PageData(request).getString("path");
if (StrUtil.isEmpty(path)) { if (StrUtil.isEmpty(path)) {
throw new RuntimeException("路径不能为空"); throw new RuntimeException("路径不能为空");
} }
@ -166,18 +167,4 @@ public class AccidentRecordsController extends BaseController {
result.put("result", "success"); // 路径 result.put("result", "success"); // 路径
return result; return result;
} }
/**
*
*
* @param path
* @param response
*/
@RequestMapping("/view/photos/{path}")
public void viewPhotos(@PathVariable("path") String path, HttpServletResponse response) {
if (StrUtil.isEmpty(path)) {
throw new RuntimeException("路径不能为空");
}
accidentRecordsService.viewPhotos(path, response);
}
} }

View File

@ -2,8 +2,8 @@ package com.zcloud.entity.accident;
import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import com.zcloud.entity.PageData;
import com.zcloud.entity.accident.dto.AccidentRecordsExcel; import com.zcloud.entity.accident.dto.AccidentRecordsExcel;
import com.zcloud.entity.system.Dictionaries;
import com.zcloud.service.system.DictionariesService; import com.zcloud.service.system.DictionariesService;
import com.zcloud.util.Jurisdiction; import com.zcloud.util.Jurisdiction;
import lombok.Data; import lombok.Data;
@ -15,8 +15,8 @@ import javax.validation.constraints.Size;
import java.io.Serializable; import java.io.Serializable;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.*;
import java.util.Optional; import java.util.concurrent.ConcurrentHashMap;
/** /**
* *
@ -171,13 +171,13 @@ public class AccidentRecords implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public AccidentRecords(AccidentRecordsExcel reader, DictionariesService service) throws RuntimeException { public AccidentRecords(AccidentRecordsExcel reader, DictionariesService service) throws Exception {
this.id = IdUtil.getSnowflake(1, 1).nextId(); this.id = IdUtil.getSnowflake(1, 1).nextId();
this.corpinfoId = reader.getCompanyName(); this.corpinfoId = reader.getCompanyName();
this.incidentNumber = reader.getIncidentNumber(); this.incidentNumber = reader.getIncidentNumber();
this.incidentName = reader.getIncidentName(); this.incidentName = reader.getIncidentName();
this.incidentType = findByName(reader.getIncidentType(), service); this.incidentType = findByName(reader.getIncidentType(), service, "8d4140a900184b60836ad1a6490fd510");
this.incidentLevel = findByName(reader.getIncidentLevel(), service); this.incidentLevel = findByName(reader.getIncidentLevel(), service, "b61a1edc59c0430c8741c5f51aa26c3c");
this.incidentNature = reader.getIncidentNature(); this.incidentNature = reader.getIncidentNature();
this.location = reader.getLocation(); this.location = reader.getLocation();
this.incidentDate = dateFormat(reader.getIncidentDate()); this.incidentDate = dateFormat(reader.getIncidentDate());
@ -196,22 +196,23 @@ public class AccidentRecords implements Serializable {
this.createdTime = new Date(); this.createdTime = new Date();
} }
private String findByName(String name, DictionariesService service) { // 缓存字典 避免频繁请求数据库
if (StrUtil.isEmpty(name)) { public static final Map<String, List<Dictionaries>> dictMap = new ConcurrentHashMap<>();
private String findByName(String bianma, DictionariesService service, String parentId) throws Exception {
if (StrUtil.isEmpty(bianma)) {
return null; return null;
} }
PageData pageData = new PageData();
pageData.put("NAME", name); if (dictMap.containsKey(parentId)) {
try { Optional<Dictionaries> optional = dictMap.get(parentId).stream().filter(d -> d.getBIANMA().equals(bianma)).findAny();
PageData data = service.findByName(pageData); return optional.map(Dictionaries::getDICTIONARIES_ID).orElse(null);
return Optional.ofNullable(data).map(pd -> pd.getString("BIANMA")).orElseThrow(() -> new RuntimeException("未找到字典数据:" + name));
} catch (RuntimeException e) {
log.error("转换字典失败", e);
throw e;
} catch (Exception e) {
log.error("获取字典失败", e);
throw new RuntimeException("获取字典失败");
} }
List<Dictionaries> dict = service.listSubDictByParentId(parentId);
dict = dict == null ? new ArrayList<>() : dict;
dictMap.put(parentId, dict);
return dict.stream().filter(d -> d != null && d.getBIANMA().equals(bianma))
.findAny().map(Dictionaries::getDICTIONARIES_ID).orElse(null);
} }
private Date dateFormat(String dateStr) { private Date dateFormat(String dateStr) {

View File

@ -70,14 +70,6 @@ public interface AccidentRecordsService {
*/ */
String importPhotos(MultipartFile file); String importPhotos(MultipartFile file);
/**
*
*
* @param path
* @param response
*/
void viewPhotos(String path, HttpServletResponse response);
/** /**
* *
* *

View File

@ -1,11 +1,9 @@
package com.zcloud.service.accident.impl; package com.zcloud.service.accident.impl;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.*; import cn.hutool.core.util.*;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.poi.excel.ExcelReader; import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil; import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter; import cn.hutool.poi.excel.ExcelWriter;
@ -16,11 +14,11 @@ import com.zcloud.entity.accident.ExcelValue;
import com.zcloud.entity.accident.dto.AccidentRecordsExcel; import com.zcloud.entity.accident.dto.AccidentRecordsExcel;
import com.zcloud.mapper.datasource.accident.AccidentRecordsMapper; import com.zcloud.mapper.datasource.accident.AccidentRecordsMapper;
import com.zcloud.service.accident.AccidentRecordsService; import com.zcloud.service.accident.AccidentRecordsService;
import com.zcloud.service.bus.ImgFilesService;
import com.zcloud.service.system.DictionariesService; import com.zcloud.service.system.DictionariesService;
import com.zcloud.util.Jurisdiction; import com.zcloud.util.*;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.session.ExecutorType; import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSession;
@ -31,8 +29,9 @@ import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -48,6 +47,7 @@ public class AccidentRecordsServiceImpl implements AccidentRecordsService {
private final SqlSessionFactory sqlSessionFactory; private final SqlSessionFactory sqlSessionFactory;
private final DictionariesService dictionariesService; private final DictionariesService dictionariesService;
private static final Map<String, String> HEADER_ALIAS_CACHE; private static final Map<String, String> HEADER_ALIAS_CACHE;
private final ImgFilesService imgFilesService;
static { static {
HEADER_ALIAS_CACHE = Arrays.stream(ReflectUtil.getFields(AccidentRecordsExcel.class)) HEADER_ALIAS_CACHE = Arrays.stream(ReflectUtil.getFields(AccidentRecordsExcel.class))
@ -72,7 +72,8 @@ public class AccidentRecordsServiceImpl implements AccidentRecordsService {
public void save(AccidentRecords accidentRecords) { public void save(AccidentRecords accidentRecords) {
accidentRecords.setId(IdUtil.getSnowflake(1, 1).nextId()); accidentRecords.setId(IdUtil.getSnowflake(1, 1).nextId());
accidentRecords.setCreatedBy(Jurisdiction.getUsername()); accidentRecords.setCreatedBy(Jurisdiction.getUsername());
accidentRecords.setCreatedTime(new Date()); Date date = Date.from(LocalDateTime.now().toInstant(ZoneOffset.of("+08:00")));
accidentRecords.setCreatedTime(date);
accidentRecords.setIsDeleted(0); accidentRecords.setIsDeleted(0);
String corpinfoId = StrUtil.isEmpty(accidentRecords.getCorpinfoId()) ? Jurisdiction.getCORPINFO_ID() : accidentRecords.getCorpinfoId(); String corpinfoId = StrUtil.isEmpty(accidentRecords.getCorpinfoId()) ? Jurisdiction.getCORPINFO_ID() : accidentRecords.getCorpinfoId();
accidentRecords.setCorpinfoId(corpinfoId); accidentRecords.setCorpinfoId(corpinfoId);
@ -83,7 +84,8 @@ public class AccidentRecordsServiceImpl implements AccidentRecordsService {
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void update(AccidentRecords accidentRecords) { public void update(AccidentRecords accidentRecords) {
accidentRecords.setUpdatedBy(Jurisdiction.getUsername()); accidentRecords.setUpdatedBy(Jurisdiction.getUsername());
accidentRecords.setUpdatedTime(new Date()); Date date = Date.from(LocalDateTime.now().toInstant(ZoneOffset.of("+08:00")));
accidentRecords.setUpdatedTime(date);
String corpinfoId = StrUtil.isEmpty(accidentRecords.getCorpinfoId()) ? Jurisdiction.getCORPINFO_ID() : accidentRecords.getCorpinfoId(); String corpinfoId = StrUtil.isEmpty(accidentRecords.getCorpinfoId()) ? Jurisdiction.getCORPINFO_ID() : accidentRecords.getCorpinfoId();
accidentRecords.setCorpinfoId(corpinfoId); accidentRecords.setCorpinfoId(corpinfoId);
Assert.isTrue(accidentRecordsMapper.updateById(accidentRecords) == 1, "更新事故记录失败"); Assert.isTrue(accidentRecordsMapper.updateById(accidentRecords) == 1, "更新事故记录失败");
@ -141,6 +143,8 @@ public class AccidentRecordsServiceImpl implements AccidentRecordsService {
sqlSession.flushStatements(); sqlSession.flushStatements();
} }
} }
// 避免刷新数据字典不生效 每次导出重新查询字典
AccidentRecords.dictMap.clear();
sqlSession.commit(); sqlSession.commit();
} catch (RuntimeException e) { } catch (RuntimeException e) {
if (sqlSession != null) { if (sqlSession != null) {
@ -161,27 +165,29 @@ public class AccidentRecordsServiceImpl implements AccidentRecordsService {
@Override @Override
public String importPhotos(MultipartFile file) { public String importPhotos(MultipartFile file) {
String fileName = StrUtil.format("{}.{}", IdUtil.getSnowflake(1, 1).nextId(), String fileName = UuidUtil.get32UUID() + "." + FilenameUtils.getExtension(file.getOriginalFilename());
FilenameUtils.getExtension(file.getOriginalFilename())); PageData pd = new PageData();
try (InputStream inputStream = file.getInputStream()) { pd.put("IMGFILES_ID", UuidUtil.get32UUID());
FileUtils.copyInputStreamToFile(inputStream, FileUtil.touch("./image/" + fileName)); pd.put("FOREIGN_KEY", UuidUtil.get32UUID());
return "./image/" + fileName; pd.put("TYPE", 117);
} catch (IOException e) { try {
String path = Const.FILEPATHFILE + UuidUtil.get32UUID() + "/" + DateUtil.getDays();
Smb.sshSftp(file, fileName, path);
pd.put("FILEPATH", path + "/" + fileName);
imgFilesService.save(pd);
return pd.getString("FILEPATH");
} catch (Exception e) {
log.error("导入图片失败", e); log.error("导入图片失败", e);
throw new RuntimeException("导入图片失败"); throw new RuntimeException("导入图片失败");
} }
} }
@Override
public void viewPhotos(String path, HttpServletResponse response) {
if (!FileUtil.exist(path)) {
throw new RuntimeException("图片不存在");
}
ServletUtil.write(response, FileUtil.touch(path));
}
@Override @Override
public void deletePhotos(String path) { public void deletePhotos(String path) {
FileUtil.del("./image/" + path); try {
Smb.deleteFile(path);
} catch (Exception e) {
throw new RuntimeException("图片删除失败");
}
} }
} }

View File

@ -3,7 +3,7 @@
<mapper namespace="com.zcloud.mapper.datasource.accident.AccidentRecordsMapper"> <mapper namespace="com.zcloud.mapper.datasource.accident.AccidentRecordsMapper">
<select id="listPage" parameterType="com.zcloud.entity.Page" resultType="pd"> <select id="listPage" parameterType="com.zcloud.entity.Page" resultType="pd">
select id, CORP_NAME as companyName, location, date_format(incident_date,'%Y-%m-%d %H:%I:%s') as 'incidentDate', incident_name as 'incidentName' select cast(accident_id AS CHAR) as id, CORP_NAME as companyName, location, date_format(incident_date,'%Y-%m-%d %H:%I:%s') as 'incidentDate', incident_name as 'incidentName'
from accident_records as ar from accident_records as ar
left join bus_corp_info as bci on ar.corpinfo_id = bci.CORPINFO_ID left join bus_corp_info as bci on ar.corpinfo_id = bci.CORPINFO_ID
<where> <where>
@ -33,10 +33,10 @@
</select> </select>
<select id="getById" resultType="com.zcloud.entity.PageData"> <select id="getById" resultType="com.zcloud.entity.PageData">
select id, select cast(accident_id AS CHAR) as id,
incident_number as incidentNumber, incident_number as incidentNumber,
incident_name as incidentName, incident_name as incidentName,
incident_type as incidentName, incident_type as incidentType,
incident_level as incidentLevel, incident_level as incidentLevel,
CORP_NAME as companyName, CORP_NAME as companyName,
incident_nature as incidentNature, incident_nature as incidentNature,
@ -56,7 +56,7 @@
report_date as reportDate report_date as reportDate
from accident_records as ar from accident_records as ar
left join bus_corp_info as bci on ar.corpinfo_id = bci.CORPINFO_ID left join bus_corp_info as bci on ar.corpinfo_id = bci.CORPINFO_ID
where ar.id = #{id} where ar.accident_id = #{id}
and ar.is_deleted = 0; and ar.is_deleted = 0;
</select> </select>
@ -64,7 +64,7 @@
insert into accident_records insert into accident_records
<trim prefix="(" suffix=")" suffixOverrides=","> <trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null"> <if test="id != null">
id, accident_id,
</if> </if>
<if test="incidentNumber != null"> <if test="incidentNumber != null">
incident_number, incident_number,
@ -145,7 +145,7 @@
values values
<trim prefix="(" suffix=")" suffixOverrides=","> <trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null"> <if test="id != null">
id, #{id},
</if> </if>
<if test="incidentNumber != null"> <if test="incidentNumber != null">
#{incidentNumber}, #{incidentNumber},
@ -254,14 +254,14 @@
<if test="updatedTime != null">updated_time = #{updatedTime},</if> <if test="updatedTime != null">updated_time = #{updatedTime},</if>
<if test="isDeleted != null">is_deleted = #{isDeleted}</if> <if test="isDeleted != null">is_deleted = #{isDeleted}</if>
</set> </set>
WHERE id = #{id} and is_deleted = 0 WHERE accident_id = #{id} and is_deleted = 0
</update> </update>
<update id="delete"> <update id="delete">
update accident_records update accident_records
set is_deleted = 1 set is_deleted = 1
where where
id IN accident_id IN
<foreach item="item" index="index" collection="ids" open="(" separator="," close=")"> <foreach item="item" index="index" collection="ids" open="(" separator="," close=")">
#{item} #{item}
</foreach> </foreach>
@ -270,10 +270,10 @@
<select id="listExcel" resultType="com.zcloud.entity.accident.dto.AccidentRecordsExcel"> <select id="listExcel" resultType="com.zcloud.entity.accident.dto.AccidentRecordsExcel">
select incident_number, select incident_number,
incident_name, incident_name,
(select NAME from sys_dictionaries_corp (select NAME from sys_dictionaries
where DICTIONARIES_ID = '' and incident_type = BIANMA) as 'incidentType', where DICTIONARIES_ID = '8d4140a900184b60836ad1a6490fd510' and BIANMA = incident_type) as 'incidentType',
(select NAME from sys_dictionaries_corp (select NAME from sys_dictionaries
where DICTIONARIES_ID = '' and incident_level = BIANMA) as 'incidentLevel', where DICTIONARIES_ID = 'b61a1edc59c0430c8741c5f51aa26c3c' and BIANMA = incident_level) as 'incidentLevel',
CORP_NAME as 'companyName', CORP_NAME as 'companyName',
incident_nature , incident_nature ,
`location`, `location`,