一.前言
本篇工作笔记为记录使用springboot+vue实现文件(html页面)导入,导出与在线编辑。
实体类 Templet :
@Data
@Table("templet")
public class Templet extends BaseEntity {
/**
* 模板主键
*/
@Name
@Prev(els = @EL("uuid(32)"))
@Column("ID")
private String id;
/**
*站点ID
*/
@Column("SITE_ID")
private String siteId;
/**
*模板名称
*/
@Column("TEMPLET_NAME")
private String templetName;
/**
* 模板英文名称
*/
@Column("TEMPLET_ENGLISH_NAME")
private String templetEnglishName;
/**
*模板文件类型
*/
@Column("TEMPLET_TYPE")
private String templetType;
/**
*模板大小
*/
@Column("TEMPLET_SIZE")
private String templetSize;
/**
*发布状态
*/
@Column("IS_PUBLISHED")
private int isPublished;
/**
*模板存放路径
*/
@Column("TEMPLET_PATH")
private String templetPath;
/**
*是否是目录
*/
@Column("IS_DIRECTORY")
private int isDirectory;
/**
*父级模板目录ID
*/
@Column("PARENT_ID")
private String parentId;
/** 所属站点*/
@One(field = "siteId")
private Site site;
@Column("TYPE")
private String type;
/**
* 文件内容
*/
@Transient
private String fileContent;
//主要用于显示模板名称
private String fileName;
public String getFileName() {
if (this.isDirectory==1) {
return this.templetName + "." + templetType;
}else{
return this.templetName;
}
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
Vue页面,文档在线编辑部分
<FormItem label="文件内容" prop="fileContent" v-show="contentFlag">
<Input v-model="dataTemplet.fileContent" type="textarea" :autosize="{minRows: 20,maxRows: 25}" placeholder="请填写文件内容"></Input>
</FormItem>
在线编辑,获取文档内容:
public Templet getReadTemplet(String id) throws Exception {
Templet templet = nutzDao.fetch(Templet.class, id);
if (templet.getIsDirectory() == 1) {
Site site = siteService.fetch(templet.getSiteId());
path = ConfigUtil.getConfigByCode("SITE_ROOT_PATH") + fileSeparator + site.getResourcePath();
String filePath = path + templet.getTempletPath();
String str = FileUtils.readFileToJson(filePath);
templet.setFileContent(str);
} else {
String templetPath = templet.getTempletPath();
templet.setTempletPath(templetPath.substring(templetPath.lastIndexOf("/")+1));
}
return templet;
}
/**
* 读取文件转化为json
*/
public static String readFileToJson(String path) throws IOException {
InputStream is = null;
InputStreamReader isr;
String str = null;
try{
isr = new InputStreamReader(new FileInputStream(path), "UTF-8");
str = inputStreamToJson(isr);
}catch (FileNotFoundException e) {
throw new FileNotFoundException("源文件没有找到");
}
return str;
}
/**
* inputStream转json
*/
private static String inputStreamToJson(InputStreamReader is) throws IOException {
String line;
String str = "";
BufferedReader br = new BufferedReader(is);
while ((line = br.readLine()) != null) {
str += new String(line.getBytes(),"UTF-8")+"\n";
}
return str;
}
在线编辑,新增或编辑更改:
public void saveNewTemplet(Templet templet) throws Exception {
String path= ConfigUtil.getConfigByCode("SITE_ROOT_PATH");
Templet tplt = this.fetch(templet.getParentId());
if (null != tplt) {
String parentTempletPath = tplt.getTempletPath();
Site site = siteService.fetch(tplt.getSiteId());
if (null != site && StringUtils.isNotBlank(site.getResourcePath())) {
templet.setSiteId(site.getId());
path = FileUtils.getSplicingPath(path, site.getResourcePath());
path = FileUtils.getSplicingPath(path, parentTempletPath);
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(FileUtils.getSplicingPath(path, templet.getTempletName()+"."+templet.getTempletType()));
if (!file.exists()) {
boolean fileFlag = file.createNewFile();
if(fileFlag){
log.info(file.getName() + "文件创建成功");
}
}
if (StringUtils.isNotBlank(templet.getFileContent())) {
templet.setTempletSize(FileUtils.getPrintSize(templet.getFileContent().length()));
}
templet.setTempletPath(FileUtils.getSplicingPath(parentTempletPath, templet.getTempletName()+"."+templet.getTempletType()));
FileWriter writer = null;
try {
writer = new FileWriter(file);
writer.write(templet.getFileContent());
}catch (Exception e){
log.debug(" 文件上传异常"+e);
}
finally {
writer.close();
}
if (StringUtils.isNotBlank(templet.getId())) {
templet.setUpdateTime(DateUtil.getTodayTimeString());
this.nutzDao.update(templet);
} else {
templet.setCreateTime(DateUtil.getTodayTimeString());
templet.setUpdateTime(DateUtil.getTodayTimeString());
this.nutzDao.insert(templet);
}
}
}
}
模板上传,导入
vue页面相关部分:
<Form ref="dataTemplet" :model="dataTemplet" :rules="ruleValidate" :label-width="130">
<FormItem label="所属目录" prop="pname">
<Input v-model="dataTemplet.pname" disabled></Input>
</FormItem>
<Row>
<Col span="12">
<FormItem label="文件上传" prop="templetPath">
<div>
<Upload
multiple
ref="upload"
accept="text/html"
:max-size="2048"
:format="['html']"
:before-upload="handleUpload"
:show-upload-list="false"
:data="dataTemplet"
:action="uploadPath"
:on-success="uploadSuccess"
>
<i-button icon="ios-cloud-upload-outline">上传</i-button>
</Upload>
</div>
</FormItem>
</Col>
<Col span="12">
<FormItem label="模板类型" prop="type">
<Select v-model="dataTemplet.type" placeholder="请选择模板类型">
<Option value="0">列表页</Option>
<Option value="1">详情页</Option>
</Select>
</FormItem>
</Col>
</Row>
<Row>
<Col span="24">
<ul v-if="file!=null" v-for="(item, index) in file" style="margin-left: 120px;">
<span>模板{{index+1}}: {{item.name == undefined ? item.fileName : item.name }}</span>
<Button type="text" @click="moveMaterial(item, index)">删除模板</Button>
</ul>
</Col>
</Row>
<FormItem label="备注" prop="remark">
<Input v-model="dataTemplet.remark" type="textarea" placeholder="请填写备注"></Input>
</FormItem>
<FormItem style="text-align: right;">
<Button type="primary" @click="templetSubmit('dataTemplet')" :loading="saveLoading">保存</Button>
<Button type="warning" @click="templetReset('dataTemplet')" style="margin-left: 8px">重置</Button>
<Button type="default" @click="hideView" style="margin-left: 8px">取消</Button>
</FormItem>
</Form>
data() {
return {
fileCount: 0,
file: [],
uploadSuccessCount:0,
uploadErrorCount:0,
deleteFile: [],
tempName: "",
uploadPath: "",
siteList: [],
saveLoading: false,
typesFlag: false,
dialogTitle: "导入模板",
ruleValidate: {
type: [{
required: true,
message: "模板类型不能为空",
trigger: "change"
}],
},
dataTemplet: {
parentId: "",
pname: ""
}
}
},
methods: {
//上传
upload() {
for (let i = 0; i < this.file.length; i++) {
let item = this.file[i];
var Img = item.name.substring(item.name.lastIndexOf('.') + 1)
if (Img === 'html') {
this.$refs.upload.post(item);
} else {
this.$Message.error({content: '上传资源只能是html格式!', duration: 3})
}
}
},
//上传成功
uploadSuccess(data) {
if ( data.resultCode === 0) {
this.uploadSuccessCount = this.uploadSuccessCount + 1;
} else {
this.uploadErrorCount = this.uploadErrorCount + 1;
}
if (this.uploadErrorCount+this.uploadSuccessCount===this.fileCount) {
this.$Message.success({
content: "共上传文件数:"+(this.uploadSuccessCount+this.uploadErrorCount)+
",成功数:"+this.uploadSuccessCount+",失败数:"+this.uploadErrorCount, duration: 3});
}
this.hideView();
},
handleUpload(file) {
this.file.push(file);
return false;
},
//移除附件
moveMaterial(file, index) {
if (file.name === undefined) {
this.deleteFile.push(file);
}
this.file.splice(index, 1);
},
//上传路径
setUploadPath() {
let token = sessionStorage.getItem("access_token");
this.uploadPath = "/iscs_gateway/cms/templet/templeUpload?access_token=" + token;
},
// 输入校验
templetSubmit(name) {
this.fileCount = this.file.length;
if (this.file.length > 0) {
this.$refs[name].validate((valid) => {
if (valid) {
this.submit();
}
})
} else {
this.$Message.error("请选择文件!")
}
},
//提交保存
submit() {
let loginUser = JSON.parse(sessionStorage.getItem("loginUser"));
this.dataTemplet.createUser = loginUser.user.userAccount;
this.dataTemplet.parentId = this.parentObj.pid;
this.upload();
}
}
后台代码:
@ApiOperation(value = "模板上传", notes = "模板上传")
@RequestMapping(value = "/templeUpload", method = {RequestMethod.POST},produces = "application/json")
public ResultMsg templeUpload(MultipartHttpServletRequest req) {
String path= ConfigUtil.getConfigByCode("SITE_ROOT_PATH");
try {
MultiValueMap<String, MultipartFile> map = req.getMultiFileMap();
String uploadPath = "";
String siteId = "";
String user = req.getParameter("createUser");
String remark = req.getParameter("remark");
String parentId = req.getParameter("parentId");
String tempType = req.getParameter("templetType");
String type = req.getParameter("type");
Templet templet = new Templet();
templet.setIsPublished(1);
templet.setParentId(parentId);
templet.setIsDirectory(1);
templet.setCreateUser(user);
templet.setRemark(remark);
templet.setType(type);
templet.setTempletType(tempType);
if (StringUtils.isNotBlank(parentId)) {
Templet parentTemplet = templetService.getTemplet(parentId);
String parentPath = "";
if (null != parentTemplet) {
siteId = parentTemplet.getSiteId();
Site site = siteService.fetch(siteId);
if (null != site && StringUtils.isNotBlank(site.getResourcePath())) {
uploadPath += site.getResourcePath();
}
uploadPath = FileUtils.getSplicingPath(uploadPath,parentTemplet.getTempletPath());
parentPath =parentTemplet.getTempletPath();
SysConfig config = configService.findConfigByCode("SITE_ROOT_PATH");
uploadPath = FileUtils.getSplicingPath(config.getConfigValue(), uploadPath);
if (map.size() != 0) {
for (List<MultipartFile> materialList : map.values()) {
for (MultipartFile mFile : materialList) {
templetService.saveFileByIO(mFile, "/", uploadPath, 0);
String fileName = mFile.getOriginalFilename();
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
String newFileName=fileName.substring(0,fileName.lastIndexOf("."));
templet.setTempletName(newFileName);
templet.setTempletPath("/"+parentPath + "/" + fileName);
templet.setSiteId(siteId);
templet.setTempletType(suffix);
templet.setTempletSize(FileUtils.getPrintSize(mFile.getSize()));
templet.setCreateTime(DateUtil.getTodayTimeString());
templet.setUpdateTime(DateUtil.getTodayTimeString());
//如果名字是一样的,更新文件
Templet templetNew=templetService.checkName(templet.getParentId(),newFileName);
if (templetNew!=null){
templetNew.setTempletSize(FileUtils.getPrintSize(mFile.getSize()));
templetNew.setTempletPath("/"+parentPath + "/" + fileName);
templet.setUpdateTime(DateUtil.getTodayTimeString());
templetService.update(templetNew);
}
else {
templetService.insert(templet);
}
}
}
}
}
}
return returnSuccess("导入成功!");
} catch (Exception e) {
log.debug(e.getMessage());
return this.returnError("查询失败","查询失败",e);
}
}
@ResponseBody
@ApiOperation(value = "模板导出", notes = "模板导出")
@RequestMapping(value = "/exportTemplet", method = {RequestMethod.GET})
public ResultMsg exportTemplet(
@ApiParam(value = "siteId", required = false) @RequestParam String siteId,
@ApiParam(value = "目录或模板id", required = false) @RequestParam String ids, HttpServletResponse response) {
Site site=null;
String path = ConfigUtil.getConfigByCode("SITE_ROOT_PATH");
String sitePath="";
if (StringUtils.isNotEmpty(siteId)){
site = siteService.fetch(siteId);
sitePath=site.getResourcePath();
}
String basePath=path + fileSeparator + sitePath ;
String pathFile="模板导出"+DateUtil.dateToStr(new Date(),5);
File toFile = new File(basePath+"/"+pathFile);
if(!toFile.exists()){
toFile.mkdirs();
}
FileOutputStream fos =null;
try {
fos = new FileOutputStream(new File(basePath+"/"+pathFile+".zip"));
} catch (FileNotFoundException e) {
log.error(e);
}
if(StringUtil.isNotEmpty(ids)){
String[] newIds=ids.split(",");
List<Templet> templetList=templetService.getTempletByIds(newIds);
for(Templet templet:templetList){
File file=null;
if (templet.getIsDirectory()==1){
String pathStr=basePath+templet.getTempletPath();
file=new File(pathStr);
} else{
String pathStr=basePath+getTempletPath(templet)+"/"+templet.getTempletPath();
file=new File(pathStr);
}
if (file.exists()) {
try {
ZipUtils.copy(file, toFile);
} catch (Exception e) {
log.error(e);
}
}
}
ZipUtils.toZip(toFile.getPath(), fos,true);
if (fos!=null){
try {
fos.close();
} catch (IOException e) {
log.error(e);
}
}
//导出文件到客户端
new ZipFileExport().downImgClient(response,pathFile+".zip",basePath+"/"+pathFile+".zip");
//导出后删除文件
ZipUtils.deleteFolder(basePath+"/"+pathFile+".zip");
ZipUtils.deleteDirectory(basePath+"/"+pathFile);
return returnSuccess("导出成功");
}else{
File file=new File(basePath+"/template");
ZipUtils.toZip(file.getPath(), fos,true);
if (fos!=null){
try {
fos.close();
} catch (IOException e) {
log.error(e);
}
}
//导出文件到客户端
new ZipFileExport().downImgClient(response,pathFile+".zip",basePath+"/"+pathFile+".zip");
//导出后删除文件
ZipUtils.deleteFolder(basePath+"/"+pathFile+".zip");
return returnSuccess("导出成功");
}
}