说在前面:
文件编辑的坑是真的多,在我反复摸索跟看别人的代码以后自己终于完成,这里给你们分享一下心得,编写不易,希望小伙伴们多多点赞!
这个跟add界面的文件上传大同小异
1.首先引入js
<th:block th:include="include :: bootstrap-fileinput-css"/>
<th:block th:include="include :: bootstrap-fileinput-js"/>
2.引入标签
<div class="file-loading">
<input id="singleFile" name="file" type="file">
div>
引入隐藏域
<input type="hidden" name="fjid" id="fjid">
3.引入js
<!--资料的实现-->
//单文件上传
$(document).ready(function(){
$("#singleFile").fileinput({
uploadUrl: prefix + "/upload",//文件上传路
dropZoneTitle: '可以将文件拖放到这里,支持文件上传',
language: 'zh',
allowedFileExtensions: ['bmp', 'gif', 'jpg', 'jpeg', 'png', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx','html', 'htm', 'txt', 'text','rar', 'zip', 'gz', 'bz2', 'pdf', 'bpmn', 'bar','db'],
showUpload: true,//是否显示上传按钮
showRemove : true, //显示移除按钮
showPreview : true, //是否显示预览
showCaption: false,//是否显示标题
fileSizeGetter: true,
previewFileType: ['image','txt','text'],
validateInitialCount:true,
preferIconicPreview: true, // 这将强制缩略图按照以下文件扩展名的图标显示
maxFileCount: 1,
autoReplace: true//自动替换
//下面的自动上传提交,建议先熟悉下面的文件点击上传
}).on('filebatchselected',function(event,data,previewId,index){
$(this).fileinput("upload");
document.getElementById('fjid').value = rsp.fjid;
log.info("return url:" + rsp.url)
log.info("return fileName:" + rsp.fileName)
log.info("return newFileName:" + rsp.newFileName)
log.info("return originalFilename: " + rsp.originalFilename)
//文件上传提交,后台返回数据前台接受
}).on('fileuploaded',function(event,data,previewId,index) {
//后台返回的数据,是一个json数据,里面是个map集合
var rsp = data.response;
//把后台返回的fjid的值赋给隐藏于的fjid属性
document.getElementById('fjid').value = rsp.fjid;
log.info("return url:" + rsp.url)
log.info("return fileName:" + rsp.fileName)
log.info("return newFileName:" + rsp.newFileName)
log.info("return originalFilename: " + rsp.originalFilename)
}).on('fileremoved',function (event, id, index){
$("input[name='" + event.currentTarget.id +"']").val('')
})
});
后台代码:
/**
* 资料上传请求(单个)
* @return
*/
@PostMapping("/upload")
@ResponseBody
public AjaxResult uploadFile(MultipartFile file) throws Exception {
try {
// 上传文件路径
String filePath = RuoYiConfig.getUploadPath();
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
//获取文件的上传路径
String url = serverConfig.getUrl() + fileName;
//得到文件的文件名
String[] split = fileName.split("/");
String fname = split[split.length - 1];
PmsFujian pmsFujian = new PmsFujian();
pmsFujian.setUrl(url);
pmsFujian.setName(fname);
pmsFujian.setCssize(file.getSize());
pmsFujian.setCsname(file.getOriginalFilename());
pmsFujian.setMkmc("工程资料");
pmsFujianService.insertPmsFujian(pmsFujian);
String fjid = pmsFujian.getFjid();
AjaxResult ajax = new AjaxResult();
ajax.put("url",url);
ajax.put("name", fname);
ajax.put("fjid",fjid);
ajax.put("fileName", fileName);
return ajax;
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}
然后调用工程的编辑方法
/**
* 修改保存工程
*/
@RequiresPermissions("common:gongcheng:edit")
@Log(title = "工程", businessType = BusinessType.UPDATE)
@PostMapping("/edit")
@ResponseBody
public AjaxResult editSave(PmsGongcheng pmsGongcheng,String fjid) {
return toAjax(pmsGongchengService.updatePmsGongcheng(pmsGongcheng,fjid));
}
updatePmsGongcheng 里面的方法执行过程
/**
* 修改工程
*
* @param pmsGongcheng 工程
* @return 结果
*/
@Override
public int updatePmsGongcheng(PmsGongcheng pmsGongcheng,String fjid,String jcfa)
{ //先更新工程数据库中的信息
int i = pmsGongchengMapper.updatePmsGongcheng(pmsGongcheng);
//判断是否传入了新文件
if (!fjid.isEmpty()) {
String gcid = pmsGongcheng.getGcid();
PmsFujian pmsFujian = pmsFujianMapper.selectPmsFujianByFjid(fjid);
pmsFujian.setGlid(gcid);
pmsFujianMapper.updatePmsFujian(pmsFujian);
}
return i;
}
这样就完成了文件上传
/** 附件主键 */
private String fjid;
/** 名称 */
@Excel(name = "名称")
private String name;
/** 路径 */
@Excel(name = "路径")
private String url;
/** 关联主键 */
@Excel(name = "关联主键")
private String glid;
/** 模块名称 */
@Excel(name = "模块名称")
private String mkmc;
/** 文件大小 */
@Excel(name = "文件大小")
private String size;
/** 文件大小(不加计算) */
@Excel(name = "文件大小", readConverterExp = "不=加计算")
private Long cssize;
/** 文件初始名称 */
@Excel(name = "文件初始名称")
private String csname;
public class PmsGongcheng extends BaseEntity {
/**
* 附件类 xyh
* */
private List<PmsFujian> pmsFujian;
...生成你的get,set方法和你的tostring
xml中使用collection标签
<collection property="pmsFujian" column="fjid" ofType="com.lrkj.pms.ztjg.common.domain.PmsFujian" resultMap="PmsFujianResult"/>
在主类的xml文件引入文件的sql
<resultMap type="com.lrkj.pms.ztjg.common.domain.PmsFujian" id="PmsFujianResult">
<result property="fjid" column="fjid" />
<result property="name" column="name" />
<result property="url" column="url" />
<result property="glid" column="glid" />
<result property="mkmc" column="mkmc" />
<result property="size" column="size" />
<result property="cssize" column="cssize" />
<result property="csname" column="csname" />
<result property="createTime" column="create_time"/>
<result property="remark" column="remark" />
resultMap>
1.首先文件的回显需要这几个东西:
initialPreview: initialPreview,
initialPreviewConfig: initialPreviewConfig,
initialPreviewAsData: true, // 默认为数据
上面的bootstrap-fileinput文件控件里面自带的属性,把这三个属性放到$(“#singleFile”).fileinput({})里面
2.编写js代码,实现initialPreview和initialPreviewConfig的实现逻辑:
var pmsFujian = [[${pmsGongcheng.pmsFujian}]];
var initialPreview = [];
var initialPreviewConfig = [];
if(pmsFujian[0].fjid == null){
pmsFujian = [];
}
if(pmsFujian != null && pmsFujian != ''){
for(var i = 0;i<pmsFujian.length;i++) {
var Fujian = pmsFujian[i];
if(Fujian != null && Fujian !=''){
var delFujian = new Object();
delFujian = generFilDel(Fujian);
//把文件的路径传到这个数组里面
initialPreview.push(Fujian.url);
//把文件的信息传到这个数组里面
initialPreviewConfig.push(delFujian);
}
}
}
//这个是判断文件属性的配置类,包含了文件的各种属性,其中url是文件的删除路径,必须要写入,与后台删除路径保持一致,key是文件删除时带到后台的ajax数据,在后台接收的是key不是fjid
function generFilDel(file) {
if(file != null && file != ''){
var type = file.url.substr(file.url.lastIndexOf('.') + 1);
if(type=='pdf'){
return {type: "pdf", size: file.cssize, caption: file.csname, url:prefix + "/deletePic", key: file.fjid, downloadUrl:file.url};
}else if(type=='text'){
return {caption: file.csname, type: "text", size: file.cssize, url:prefix + "/deletePic", key: file.fjid , downloadUrl:file.url};
}else if(type=='mp4'){
return {type: "video", size: file.cssize, filetype: "video/mp4", caption: file.csname, url:prefix + "/deletePic", key: file.fjid , downloadUrl:file.url};
}else if(type=='txt'){
return {type: "txt", size: file.cssize, caption: file.csname, url:prefix + "/deletePic", key: file.fjid , downloadUrl:file.url};
}else if(type=='db'){
return {type: "db", size: file.cssize, caption: file.csname, url:prefix + "/deletePic", key: file.fjid , downloadUrl:file.url};
}else{
return {caption: file.csname, size: file.cssize, url: prefix + "/deletePic", key: file.fjid};
}
}
}
文件删除直接调用bootstrap里面的filesuccessremove方法
on('filesuccessremove',function(event,data,previewId,index){
for (var i = 0; i < pmsFujian.length; i++) {
if (pmsFujian[i].fjid == data) {
delete pmsFujian[i];
}
}
因为咱们在initialPreviewConfig传入了删除路径和删除时所带的文件id,所以先配置好js代码:
$("#singleFile").fileinput({
//添加文件的删除路径
deleteUrl: prefix + "/deletePic",
后台代码:
/**
*删除文件
*
*/
@PostMapping("/deletePic")
@ResponseBody
//传入从前台过来的key
public AjaxResult delete(String key){
return toAjax(pmsFujianService.deletePmsFujianByFjid(key));
}
这样就实现了前端实现文件移除时后端也删除了文件数据库中对应的文件信息