#I85QPE 处理附件列表问题,优化文件上传逻辑

This commit is contained in:
sswiki
2023-10-07 15:02:52 +08:00
parent de11195aa9
commit 346c63d55f
13 changed files with 178 additions and 161 deletions

View File

@@ -0,0 +1,24 @@
package com.zyplayer.doc.core.enums;
import lombok.Getter;
/**
* 文件存储路径
*
* @author 暮光:城中城
* @since 2023-10-06
*/
public enum PageFileSource {
UPLOAD_FILES(1, "手动上传的附件"),
PASTE_FILES(2, "页面粘贴的图片或文件"),
;
@Getter
private Integer source;
@Getter
private String desc;
PageFileSource(Integer source, String desc) {
this.source = source;
this.desc = desc;
}
}

View File

@@ -90,4 +90,9 @@ public class WikiPageFile implements Serializable {
* 文件大小
*/
private Long fileSize;
/**
* 文件来源 1=上传的文件 2=文档内粘贴的图片或文件
*/
private Integer fileSource;
}

View File

@@ -147,6 +147,7 @@ CREATE TABLE `wiki_page_file` (
`del_flag` tinyint(4) NULL DEFAULT 0 COMMENT '0=有效 1=删除',
`download_num` int(11) NOT NULL DEFAULT 0 COMMENT '下载次数',
`file_size` bigint NULL COMMENT '文件大小',
`file_source` TINYINT(4) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uk_uuid`(`uuid`) USING BTREE COMMENT '文件ID'
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;

View File

@@ -4,18 +4,18 @@
-- ------------------------从1.1.5版本升级------------------------
CREATE TABLE `wiki_page_template`
(
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '模板信息逐渐',
`space_id` bigint(20) NULL DEFAULT NULL COMMENT '空间id',
`page_id` bigint(20) NULL DEFAULT NULL COMMENT '模板挂载文档id',
`tag_name` varchar(200) CHARACTER SET utf8mb4 NULL DEFAULT NULL COMMENT '标签信息',
`share_status` tinyint(1) NULL DEFAULT NULL COMMENT '模板公开状态0-个人模板1-公共模板)',
`created` datetime NULL DEFAULT NULL COMMENT '创建时间',
`create_user_id` bigint(20) NULL DEFAULT NULL COMMENT '创建人id',
`create_user` varchar(200) CHARACTER SET utf8mb4 NULL DEFAULT NULL COMMENT '创建人名称',
`yn` tinyint(1) NOT NULL default '1',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB
AUTO_INCREMENT = 1
CHARACTER SET = utf8mb4 COMMENT = '模板信息表';
CREATE TABLE `wiki_page_template` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '模板信息逐渐',
`space_id` bigint(20) NULL DEFAULT NULL COMMENT '空间id',
`page_id` bigint(20) NULL DEFAULT NULL COMMENT '模板挂载文档id',
`tag_name` varchar(200) CHARACTER SET utf8mb4 NULL DEFAULT NULL COMMENT '标签信息',
`share_status` tinyint(1) NULL DEFAULT NULL COMMENT '模板公开状态0-个人模板1-公共模板)',
`created` datetime NULL DEFAULT NULL COMMENT '创建时间',
`create_user_id` bigint(20) NULL DEFAULT NULL COMMENT '创建人id',
`create_user` varchar(200) CHARACTER SET utf8mb4 NULL DEFAULT NULL COMMENT '创建人名称',
`yn` tinyint(1) NOT NULL default '1',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COMMENT = '模板信息表';
ALTER TABLE `wiki_page_file` ADD COLUMN `file_source` TINYINT(4) NOT NULL DEFAULT '1';

View File

@@ -49,7 +49,7 @@ const dragChangeRightAsideWidth = () => {
background: #fafafa;
&:hover {
background: #ccc;
background: #2a85f6;
}
}
</style>

View File

@@ -17,7 +17,7 @@
</a-menu-item>
<a-menu-item key="3">
<el-tooltip content="支持MDZIP格式图片和MD文件请放到同级目录并配置同级相对路径" placement="right-start" :show-after="300">
<a-upload v-model:file-list="fileList" name="file" :multiple="false" :customRequest="doAUpload">
<a-upload v-model:file-list="fileList" name="file" :multiple="false" :customRequest="doAUpload" class="import-upload">
<IconParkAfferent/> 导入
</a-upload>
</el-tooltip>
@@ -45,7 +45,7 @@ import axios from "axios";
import IconDocument from '@/components/base/IconDocument.vue'
let router = useRouter();
let uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + '/zyplayer-doc-wiki/page/file/upload');
let uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + '/zyplayer-doc-wiki/page/file/import/upload');
let fileList = ref([]);
let emit = defineEmits(['choosePageIdFunc', 'doGetPageList', 'createWikiByTemplate'])
let props = defineProps({
@@ -55,13 +55,12 @@ let props = defineProps({
funcId: Number
});
const doAUpload = (data) => {
let formData = new FormData()
formData.append('files', data.file)
formData.append('pageId', props.choosePageId)
let formData = new FormData();
formData.append('files', data.file);
formData.append('pageId', props.choosePageId);
if (props.choosePageId === 0) {
formData.append('id', props.choiceSpace)
formData.append('id', props.choiceSpace);
}
formData.append('importFlag', true)
axios({
url: uploadFileUrl.value,
method: 'post',
@@ -70,21 +69,21 @@ const doAUpload = (data) => {
timeout: 10000,
withCredentials: true,
}).then((res) => {
fileList.value = []
fileList.value = [];
if (res.data.errCode === 200) {
ElMessage.success('导入成功')
ElMessage.success('导入成功');
}
if (res.data.errCode === 300) {
ElMessage.warning(res.data.errMsg)
ElMessage.warning('文件太多可能超时,如果是超时,请稍等后刷新查看列表~')
ElMessage.warning(res.data.errMsg);
ElMessage.warning('文件太多可能超时,如果是超时,请稍等后刷新查看列表~');
}
emit('doGetPageList', null)
emit('doGetPageList', null);
}).catch((e) => {
fileList.value = []
emit('doGetPageList', null)
ElMessage.error('导入失败:' + e.message)
})
fileList.value = [];
emit('doGetPageList', null);
ElMessage.error('导入失败:' + e.message);
});
}
const choosePageIdFunc = (id) => {
emit('choosePageIdFunc', id)
@@ -123,8 +122,18 @@ const createWiki = (editorType, parentId) => {
<style lang="scss">
.add-menu-dropdown-btn {
padding: 0 8px;
height: 35px;
margin-top: -1px;
padding: 0 8px;
height: 35px;
margin-top: -1px;
}
.import-upload {
.ant-upload-select {
display: block;
.ant-upload {
display: block;
}
}
}
</style>

View File

@@ -1,6 +1,7 @@
package com.zyplayer.doc.wiki.batch;
import cn.hutool.core.io.FileUtil;
import com.zyplayer.doc.core.json.DocResponseJson;
import com.zyplayer.doc.data.repository.manage.entity.WikiPageFile;
import com.zyplayer.doc.wiki.batch.entry.DocEntry;
import com.zyplayer.doc.wiki.batch.strategy.ConditionalStrategySelector;
@@ -36,7 +37,7 @@ public class BatchDocImportManager {
* @author Sh1yu
* @since 2023年7月13日
*/
public String importBatchDoc(WikiPageFile wikiPageFile, MultipartFile file) {
public DocResponseJson<Object> importBatchDoc(WikiPageFile wikiPageFile, MultipartFile file) {
String suffix = FileUtil.getSuffix(file.getOriginalFilename());
try {
IFileStrategy strategy = conditionalStrategySelector.getStrategy(suffix, IFileStrategy.class);
@@ -44,20 +45,17 @@ public class BatchDocImportManager {
if (log.isInfoEnabled()) {
log.info("暂时不支持{}格式文件的导入", suffix);
}
return "暂时不支持" + suffix + "格式文件的导入";
return DocResponseJson.warn("暂时不支持" + suffix + "格式文件的导入");
}
if (log.isInfoEnabled()) {
log.info("文档导入的格式为{},选择的策略为{}", suffix, strategy.getClass().getName());
}
String info = strategy.file(uploadPath, wikiPageFile, file);
if (null == info) {
return info;
}
strategy.file(uploadPath, wikiPageFile, file);
} catch (Exception e) {
log.warn("导入文件发生错误{}", e.getMessage());
return "导入文件发生错误!";
log.warn("导入文件发生错误{}", e.getMessage());
return DocResponseJson.warn("导入文件发生错误!");
}
return null;
return DocResponseJson.ok();
}
/**

View File

@@ -13,5 +13,5 @@ import java.io.IOException;
* @since 20230717
*/
public interface IFileStrategy extends IConditionalStrategy {
public String file(String uploadPath, WikiPageFile wikiPageFile, MultipartFile file)throws IOException;
void file(String uploadPath, WikiPageFile wikiPageFile, MultipartFile file)throws IOException;
}

View File

@@ -1,13 +1,14 @@
package com.zyplayer.doc.wiki.batch.strategy.file;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.zyplayer.doc.data.repository.manage.entity.WikiPage;
import com.zyplayer.doc.data.repository.manage.entity.WikiPageFile;
import com.zyplayer.doc.data.service.manage.WikiPageService;
import com.zyplayer.doc.wiki.service.WikiPageFileServiceEx;
import com.zyplayer.doc.wiki.service.WikiPageUploadService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.codec.Charsets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
@@ -22,38 +23,32 @@ import java.io.IOException;
@Component
@RequiredArgsConstructor
public class MDFileStrategy implements IFileStrategy {
private final WikiPageService wikiPageService;
private final WikiPageUploadService wikipageUploadService;
private final WikiPageFileServiceEx wikiPageFileServiceEx;
@Override
public String file(String uploadPath, WikiPageFile wikiPageFile, MultipartFile file)throws IOException{
Long pageID = wikiPageFile.getPageId();
WikiPage page = wikiPageService.getById(pageID);
WikiPage wikiPage = new WikiPage();
wikiPage.setName(file.getOriginalFilename().substring(0,file.getOriginalFilename().indexOf(".")));
Long spaceId = wikiPageFile.getId();
Long id = wikiPageFile.getPageId();
if (null != page) {
spaceId = page.getSpaceId();
id = page.getId();
}
wikiPage.setSpaceId(spaceId);
wikiPage.setParentId(id);
wikiPage.setEditorType(2);
String context ="";
wikipageUploadService.update(wikiPage,context,context);
wikiPageFile.setPageId(wikiPage.getId());
wikiPageFileServiceEx.uploadFile(wikiPageFile,file,0);
String path = uploadPath + "/" + DateTime.now().toString("yyyy/MM/dd") + "/"+wikiPageFile.getUuid()+wikiPageFile.getFileName().substring(wikiPageFile.getFileName().indexOf("."));
context = FileUtil.readUtf8String(path);
wikipageUploadService.update(wikiPage,context,context);
return null;
}
@Override
public String getCondition() {
return "md";
}
private final WikiPageService wikiPageService;
private final WikiPageUploadService wikipageUploadService;
@Override
public void file(String uploadPath, WikiPageFile wikiPageFile, MultipartFile file) throws IOException {
String fileName = StringUtils.defaultString(file.getOriginalFilename(), "新建文档");
Long pageId = wikiPageFile.getPageId();
WikiPage page = wikiPageService.getById(pageId);
WikiPage wikiPage = new WikiPage();
wikiPage.setName(fileName.substring(0, fileName.indexOf(".")));
Long spaceId = wikiPageFile.getId();
Long id = wikiPageFile.getPageId();
if (null != page) {
spaceId = page.getSpaceId();
id = page.getId();
}
wikiPage.setSpaceId(spaceId);
wikiPage.setParentId(id);
wikiPage.setEditorType(2);
String context = IoUtil.read(file.getInputStream(), Charsets.UTF_8);
wikipageUploadService.update(wikiPage, context, context);
}
@Override
public String getCondition() {
return "md";
}
}

View File

@@ -5,6 +5,7 @@ import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ZipUtil;
import com.zyplayer.doc.core.exception.ConfirmException;
import com.zyplayer.doc.data.config.security.DocUserDetails;
import com.zyplayer.doc.data.config.security.DocUserUtil;
import com.zyplayer.doc.data.repository.manage.entity.WikiPage;
@@ -43,7 +44,7 @@ public class ZIPFileStrategy implements IFileStrategy {
private final WikiPageService wikiPageService;
@Override
public String file(String uploadPath, WikiPageFile wikiPageFile, MultipartFile file) throws IOException {
public void file(String uploadPath, WikiPageFile wikiPageFile, MultipartFile file) throws IOException {
Long pageID = wikiPageFile.getPageId();
WikiPage page = wikiPageService.getById(pageID);
String path = uploadPath + "/" + DateTime.now().toString("yyyy/MM/dd") + "/";
@@ -80,7 +81,7 @@ public class ZIPFileStrategy implements IFileStrategy {
File newFile = new File(savePath);
if (!newFile.exists() && !newFile.mkdirs()) {
log.warn("创建文件夹失败{}", savePath);
return "创建文件夹失败";
throw new ConfirmException("创建文件夹失败");
}
String simpleUUID = IdUtil.simpleUUID();
savePath += simpleUUID + "." + FileUtil.getSuffix(media.getOldFileLink());
@@ -93,7 +94,7 @@ public class ZIPFileStrategy implements IFileStrategy {
} catch (Exception e) {
e.printStackTrace();
log.error("保存文件失败{}", savePath);
return "保存文件失败";
throw new ConfirmException("保存文件失败");
}
mediaWikiPageFile.setFileSize(FileUtil.size(mediaFile));
mediaWikiPageFile.setUuid(simpleUUID);
@@ -109,7 +110,6 @@ public class ZIPFileStrategy implements IFileStrategy {
}
wikiPageUploadService.update(wikiPage, context, context);
}
return null;
}
@Override

View File

@@ -1,9 +1,11 @@
package com.zyplayer.doc.wiki.controller;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zyplayer.doc.core.annotation.AuthMan;
import com.zyplayer.doc.core.enums.PageFileSource;
import com.zyplayer.doc.core.exception.ConfirmException;
import com.zyplayer.doc.core.json.DocResponseJson;
import com.zyplayer.doc.core.json.ResponseJson;
@@ -109,21 +111,22 @@ public class WikiPageController {
if (SpaceType.isOthersPrivate(wikiSpaceSel.getType(), currentUser.getUserId(), wikiSpaceSel.getCreateUserId())) {
return DocResponseJson.warn("您没有权限查看该空间的文章详情!");
}
UpdateWrapper<WikiPageContent> wrapper = new UpdateWrapper<>();
wrapper.eq("page_id", wikiPage.getId());
LambdaQueryWrapper<WikiPageContent> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(WikiPageContent::getPageId, wikiPage.getId());
WikiPageContent pageContent = wikiPageContentService.getOne(wrapper);
UpdateWrapper<WikiPageFile> wrapperFile = new UpdateWrapper<>();
wrapperFile.eq("page_id", wikiPage.getId());
wrapperFile.eq("del_flag", 0);
// 查询附件
LambdaQueryWrapper<WikiPageFile> wrapperFile = new LambdaQueryWrapper<>();
wrapperFile.eq(WikiPageFile::getPageId, wikiPage.getId());
wrapperFile.eq(WikiPageFile::getDelFlag, 0);
wrapperFile.eq(WikiPageFile::getFileSource, PageFileSource.UPLOAD_FILES.getSource());
List<WikiPageFile> pageFiles = wikiPageFileService.list(wrapperFile);
for (WikiPageFile pageFile : pageFiles) {
pageFile.setFileUrl("zyplayer-doc-wiki/common/file?uuid=" + pageFile.getUuid());
}
UpdateWrapper<WikiPageZan> wrapperZan = new UpdateWrapper<>();
wrapperZan.eq("page_id", wikiPage.getId());
wrapperZan.eq("create_user_id", currentUser.getUserId());
wrapperZan.eq("yn", 1);
LambdaQueryWrapper<WikiPageZan> wrapperZan = new LambdaQueryWrapper<>();
wrapperZan.eq(WikiPageZan::getPageId, wikiPage.getId());
wrapperZan.eq(WikiPageZan::getCreateUserId, currentUser.getUserId());
wrapperZan.eq(WikiPageZan::getYn, 1);
WikiPageZan pageZan = wikiPageZanService.getOne(wrapperZan);
WikiPageContentVo vo = new WikiPageContentVo();
vo.setWikiPage(wikiPageSel);

View File

@@ -2,6 +2,7 @@ package com.zyplayer.doc.wiki.controller;
import com.alibaba.fastjson.JSONObject;
import com.zyplayer.doc.core.annotation.AuthMan;
import com.zyplayer.doc.core.enums.PageFileSource;
import com.zyplayer.doc.core.json.DocResponseJson;
import com.zyplayer.doc.core.json.ResponseJson;
import com.zyplayer.doc.data.repository.manage.entity.WikiPageFile;
@@ -31,64 +32,43 @@ import java.util.Map;
@RequestMapping("/zyplayer-doc-wiki/page/file")
@RequiredArgsConstructor
public class WikiPageFileController {
private final WikiPageFileServiceEx wikiPageFileServiceEx;
private final BatchDocImportManager batchDocImportManger;
/* @PostMapping("/list")
public ResponseJson<List<WikiPageFile>> list(WikiPageFile wikiPageFile) {
// TODO 检查space是否开放访问
return DocResponseJson.ok(wikiPageFileServiceEx.list(wikiPageFile));
}*/
@PostMapping("/delete")
public ResponseJson<Object> delete(WikiPageFile wikiPageFile) {
String info = wikiPageFileServiceEx.delete(wikiPageFile);
if (null != info) {
return DocResponseJson.warn(info);
}
return DocResponseJson.ok();
}
@PostMapping("/wangEditor/upload")
public Map<String, Object> wangEditorUpload(WikiPageFile wikiPageFile, @RequestParam("files") MultipartFile file) {
Map<String, Object> resultMap = new HashMap<>();
Object result = wikiPageFileServiceEx.basicUpload(wikiPageFile, file);
DocResponseJson docResponseJson = DocResponseJson.warn("处理失败");
if (result instanceof WikiPageFile) {
docResponseJson = DocResponseJson.ok(result);
} else if (result != null) {
docResponseJson = DocResponseJson.error((String) result);
}
if (!docResponseJson.isOk()) {
resultMap.put("errno", 1);
resultMap.put("message", docResponseJson.getErrMsg());
} else {
resultMap.put("errno", 0);
resultMap.put("data", new JSONObject().fluentPut("url", wikiPageFile.getFileUrl()));
}
return resultMap;
}
@PostMapping("/upload")
public ResponseJson upload(WikiPageFile wikiPageFile, @RequestParam("files") MultipartFile file, boolean importFlag) {
if (importFlag) {
String info = batchDocImportManger.importBatchDoc(wikiPageFile, file);
if (null == info) {
return DocResponseJson.ok();
}
return DocResponseJson.warn(info);
}
Object result = wikiPageFileServiceEx.basicUpload(wikiPageFile, file);
if (result instanceof WikiPageFile) {
return DocResponseJson.ok(result);
} else if (result != null) {
return DocResponseJson.warn((String) result);
}
return DocResponseJson.warn("未知异常");
}
private final WikiPageFileServiceEx wikiPageFileServiceEx;
private final BatchDocImportManager batchDocImportManger;
@PostMapping("/delete")
public ResponseJson<Object> delete(WikiPageFile wikiPageFile) {
String info = wikiPageFileServiceEx.delete(wikiPageFile);
if (null != info) {
return DocResponseJson.warn(info);
}
return DocResponseJson.ok();
}
@PostMapping("/wangEditor/upload")
public Map<String, Object> wangEditorUpload(WikiPageFile wikiPageFile, @RequestParam("files") MultipartFile file) {
Map<String, Object> resultMap = new HashMap<>();
wikiPageFile.setFileSource(PageFileSource.PASTE_FILES.getSource());
DocResponseJson<Object> docResponseJson = wikiPageFileServiceEx.basicUpload(wikiPageFile, file);
if (!docResponseJson.isOk()) {
resultMap.put("errno", 1);
resultMap.put("message", docResponseJson.getErrMsg());
} else {
resultMap.put("errno", 0);
resultMap.put("data", new JSONObject().fluentPut("url", wikiPageFile.getFileUrl()));
}
return resultMap;
}
@PostMapping("/import/upload")
public ResponseJson importUpload(WikiPageFile wikiPageFile, @RequestParam("files") MultipartFile file) {
return batchDocImportManger.importBatchDoc(wikiPageFile, file);
}
@PostMapping("/upload")
public ResponseJson upload(WikiPageFile wikiPageFile, @RequestParam("files") MultipartFile file) {
wikiPageFile.setFileSource(PageFileSource.UPLOAD_FILES.getSource());
return wikiPageFileServiceEx.basicUpload(wikiPageFile, file);
}
}

View File

@@ -3,6 +3,8 @@ package com.zyplayer.doc.wiki.service;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zyplayer.doc.core.json.DocResponseJson;
import com.zyplayer.doc.core.json.ResponseJson;
import com.zyplayer.doc.data.config.security.DocUserDetails;
import com.zyplayer.doc.data.config.security.DocUserUtil;
import com.zyplayer.doc.data.repository.manage.entity.UserMessage;
@@ -82,30 +84,30 @@ public class WikiPageFileServiceEx {
userMessageService.addWikiMessage(userMessage);
return null;
}
public Object basicUpload(WikiPageFile wikiPageFile, MultipartFile file) {
public DocResponseJson<Object> basicUpload(WikiPageFile wikiPageFile, MultipartFile file) {
DocUserDetails currentUser = DocUserUtil.getCurrentUser();
Long pageId = wikiPageFile.getPageId();
if (pageId == null || pageId <= 0) {
return "未指定附件关联的文档";
return DocResponseJson.warn("未指定附件关联的文档");
}
WikiPage wikiPageSel = wikiPageService.getById(pageId);
WikiSpace wikiSpaceSel = wikiSpaceService.getById(wikiPageSel.getSpaceId());
// 权限判断
String canUploadFile = wikiPageAuthService.canUploadFile(wikiSpaceSel, wikiPageSel.getId(), currentUser.getUserId());
if (canUploadFile != null) {
return canUploadFile;
return DocResponseJson.warn(canUploadFile);
}
String info = this.uploadFile(wikiPageFile, file,0);
String info = this.uploadFile(wikiPageFile, file, 0);
if (null != info) {
return info;
return DocResponseJson.warn(info);
}
// 给相关人发送消息
UserMessage userMessage = userMessageService.createUserMessage(currentUser, pageId, wikiPageSel.getName(), DocSysType.WIKI, UserMsgType.WIKI_PAGE_UPLOAD);
userMessage.setAffectUserId(wikiPageSel.getCreateUserId());
userMessage.setAffectUserName(wikiPageSel.getCreateUserName());
userMessageService.addWikiMessage(userMessage);
return wikiPageFile;
return DocResponseJson.ok(wikiPageFile);
}
/**