前言:本篇博客主要介绍ElementUI中el upload上传控件的使用,包含前后台代码。
1.前端控件主要代码:
增加:
<!-- 写信 -->
<div class="tabCon">
<div class="tabcon" v-show="nowIndex==0">
<el-form :model="formData" ref="formData" :rules="formRule" style="margin-top: 3%;">
<el-form-item label="主题" prop="theme" label-width="20%">
<el-input v-model="formData.theme"></el-input>
</el-form-item>
<!-- 添加附件 -->
<el-form-item label-width="20%">
<div class="upload-box">
<el-upload
ref="upload"
action="/"
:http-request="upload"
accept="image/png, image/jpg, image/jpeg, image/gif, .txt, .doc, .docx, .xls, .xlsx, .pdf, .zip, .rar"
:limit=limitNum
:on-remove="handleRemove"
:before-remove="beforeRemove"
:auto-upload="true"
:before-upload="beforeUploadFile"
:on-change="fileChange"
:on-exceed="exceedFile"
:on-success="handleSuccess"
:on-error="handleError"
:on-progress="uploadFileProcess"
:file-list="fileList">
<el-button size="small" type="text" icon="iconfont icon-lianjie"> 添加附件</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg, jpeg, png, gif, txt, doc, docx, xls, xlsx, pdf, zip, rar文件,且不超过100MB!</div>
</el-upload>
<el-progress v-if="progressFlag" :percentage="loadProgress"></el-progress>
</div>
</el-form-item>
<el-form-item label="正文" label-width="20%">
<div class="md-layout-item md-medium-size-100 md-xsmall-size-100 md-size-100">
<wang-editor v-model="formData.content" :isClear="isClear"></wang-editor>
</div>
</el-form-item>
<el-form-item class="btn-select">
<el-button @click="personalForward">个人发送</el-button>
<el-button @click="groupForward">群组发送</el-button>
<el-button type="info" plain @click="saveDraft">存草稿</el-button>
</el-form-item>
</el-form>
</div>
修改:
<!-- 修改草稿箱 -->
<div class="tabCon">
<div class="tabcon">
<el-form :model="formData" ref="formData" :rules="formRule" style="margin: 3% 6%;">
<el-form-item label="主题" prop="theme" label-width="20%">
<el-input v-model="formData.theme"></el-input>
</el-form-item>
<!-- 修改附件 -->
<el-form-item label-width="20%">
<div class="upload-box">
<el-upload
:headers="headers"
ref="upload"
action=""
:http-request="upload"
accept="image/png, image/jpg, image/jpeg, image/gif, .txt, .doc, .docx, .xls, .xlsx, .pdf, .zip, .rar"
:on-remove="handleRemove"
:before-remove="beforeRemove"
:limit="limitNum"
:auto-upload="true"
:before-upload="beforeUploadFile"
:on-change="fileChange"
:on-exceed="exceedFile"
:on-success="handleSuccess"
:on-error="handleError"
:on-preview="handlePreview"
:file-list="fileList">
<el-button size="small" type="text" icon="iconfont icon-lianjie"> 修改附件</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg, jpeg, png, gif, txt, doc, docx, xls, xlsx, pdf, zip, rar文件,且不超过100MB!</div>
</el-upload>
</div>
</el-form-item>
<el-form-item label="正文" label-width="20%">
<div class="md-layout-item md-medium-size-100 md-xsmall-size-100 md-size-100">
<wang-editor :content="formData.content" :isClear="isClear"></wang-editor>
</div>
</el-form-item>
<el-form-item class="btn-select" style="margin-top: 3%;">
<!-- <el-button @click="personalForward">个人发送</el-button>
<el-button @click="groupForward">群组发送</el-button> -->
<el-button type="info" plain @click="updateDraft">修改草稿</el-button>
</el-form-item>
</el-form>
</div>
</div>
2.前端主要方法代码:
增加:
//进度条显示
uploadFileProcess(event, file, fileList) {
this.progressFlag = true; // 显示进度条
this.loadProgress = parseInt(event.percent); // 动态获取文件上传进度
if (this.loadProgress >= 100) {
this.loadProgress = 100
setTimeout( () => {
this.progressFlag = false}, 1000) // 一秒后关闭进度条
}
},
//移除附件前的操作
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${
file.name }?`);
},
//移除附件执行的操作
handleRemove(file, fileList) {
console.log(file, fileList);
this.formData.file=null;
},
// 文件超出个数限制时的钩子
exceedFile(files, fileList) {
this.$notify.warning({
title: '警告',
message: `只能选择 ${
this.limitNum} 个文件,当前共选择了 ${
files.length + fileList.length} 个`
});
},
// 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传
beforeUploadFile(file) {
console.log('before upload')
console.log(file)
let extension = file.name.substring(file.name.lastIndexOf('.')+1)
console.log(extension)
let size = file.size / 1024 / 1024
console.log(size)
//文件格式类型限定
const isPNG = extension === 'png'
const isJPG = extension === 'jpg'
const isJPEG = extension === 'jpeg'
const isGIF = extension === 'gif'
const isTXT = extension === 'txt'
const isDOC = extension === 'doc'
const isDOCX = extension === 'docx'
const isXLS = extension === 'xls'
const isXLSX = extension === 'xlsx'
const isPDF = extension === 'pdf'
const isZIP = extension === 'zip'
const isRAR = extension === 'rar'
//文件格式类型过滤
if(!isPNG && !isJPEG && !isJPG && !isGIF && !isTXT && !isDOC && !isDOCX && !isXLS &&!isXLSX && !isPDF && !isZIP && !isRAR) {
this.$notify.warning({
title: '警告',
message: '只能上传后缀是jpg, jpeg, png, gif, txt, doc, docx, xls, xlsx, pdf, zip, rar的文件'
});
}
if(size > 100) {
this.$notify.warning({
title: '警告',
message: `文件大小不得超过100M`
});
}
},
// 文件状态改变时的钩子
fileChange(file, fileList) {
console.log('change')
console.log("file"+file)
this.formData.file = file.raw
console.log("this.formData.file.length:"+this.formData.file.size)
this.fileList=fileList
console.log("this.fileList.length:"+fileList.length)
},
// 文件上传成功时的钩子
handleSuccess(res, file, fileList) {
this.$notify.success({
title: '成功',
message: `文件上传成功`
});
},
// 文件上传失败时的钩子
handleError(err, file, fileList) {
this.$notify.error({
title: '错误',
message: `文件上传失败`
});
},
//模拟文件上传成功方法
upload(){
},
//保存到草稿
saveDraft(){
if(this.formData.theme==''){
this.$message.warning('邮件标题不能为空,请重新输入!');
return;
}
if(this.formData.content==''){
this.$message.warning('邮件内容不能为空,请重新输入!');
return;
}
let params = new FormData();
params.append('title',this.formData.theme);
params.append('content',this.formData.content);
params.append('multipartFile',this.formData.file);
this.setPageLoading();
api.saveDraft(params).then(respond => {
if (respond.status === 200) {
let respondData = respond.data;
if (respondData.status === 200) {
this.groupForwardingDialog = false;
this.$message({
type: 'success',
message: '保存草稿成功!'
});
//跳转到草稿箱页面
this.nowIndex=3;
this.getDraftList();
} else {
this.$message.error(respond.data.message);
}
pageLoading.close();
} else {
this.$message.error('服务器连接异常,请刷新后重新操作!');
}
});
},
修改:
//得到草稿邮件详细信息
getOneDraft(){
let params = {
id:this.draftId
}
// console.log('ddsdsfs>>>',params);
api.getOneDraft(params).then(respond => {
if (respond.status === 200) {
let respondData = respond.data;
this.formData.theme = respondData.data.messageDraft.title;
this.formData.content = respondData.data.messageDraft.content;
this.draftInfo.addTime = respondData.data.messageDraft.addTime;
if(respondData.data.attachment != null){
this.draftInfo.fileName = respondData.data.attachment.originalName;
this.draftInfo.fileUrl = respondData.data.attachment.fileUrl;
this.draftInfo.fileSize = respondData.data.attachment.fileSize;
// this.fileList[0].name=respondData.data.attachment.originalName;
// this.fileList[0].url=respondData.data.attachment.fileUrl;
this.fileList.push({
name: respondData.data.attachment.originalName, url: respondData.data.attachment.fileUrl });
}
console.log(this.draftInfo);
console.log(this.formData);
} else {
this.$message.error('服务器连接异常,请刷新后重新操作!');
}
});
},
//修改草稿箱信息
updateDraft(param){
console.log("this.filelist",this.fileList);
if(this.formData.theme==''){
this.$message.warning('邮件标题不能为空,请重新输入!');
return;
}
if(this.formData.content==''){
this.$message.warning('邮件内容不能为空,请重新输入!');
return;
}
let params = new FormData();
params.append('id',this.draftId);
params.append('title',this.formData.theme);
params.append('content',this.formData.content);
params.append('multipartFile',this.formData.file);
params.append('isChanged',this.formData.isChanged);
console.log('ddsdsfs>>>',params);
api.updateDraft(params).then(respond => {
if (respond.status === 200) {
let respondData = respond.data;
if (respondData.status === 200) {
this.groupForwardingDialog = false;
this.$message({
type: 'success',
message: '修改草稿成功!'
});
// 跳转到邮箱页面
this.$router.push({
name: "InsideLetter"
});
} else {
this.$message.error(respond.data.message);
}
} else {
this.$message.error('服务器连接异常,请刷新后重新操作!');
}
});
},
3.后台控制器主要代码:
/**
* 保存个人邮件到草稿箱
*
* @param jwt
* @param title
* @param content
* @param multipartFile
* @return
*/
@ApiOperation(value = "保存个人邮件到草稿箱")
@PostMapping("/saveDraft")
@PreAuthorize("hasAnyAuthority('teacher_base','admin_base','student_base')")
public HttpRespond saveDraft(@RequestHeader("Authorization") String jwt,
@RequestParam(value = "title") String title,
@RequestParam(value = "content") String content,
@RequestParam(value = "multipartFile",required=false) MultipartFile multipartFile) {
// 获取当前登录的用户信息: userId,
HashMap<String, String> userInfo = JsonInfoUtils.getUserInfo(jwt);
if (userInfo == null) {
return HttpRespond.unauthorized();
}
Integer userId = Integer.valueOf(userInfo.get("userId"));
// 开启事务管理
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus status = txManager.getTransaction(def);
String tip = "";
try {
MessageDraft messageDraft = new MessageDraft();
//封装数据
messageDraft.setUserId(userId);
messageDraft.setTitle(title);
messageDraft.setType(0);
//保存个人草稿
draftService.save(messageDraft);
//将邮件草稿箱内容存入mongodb中
MessageDraftContent messageDraftContent=new MessageDraftContent();
messageDraftContent.setMessagedraft_id(messageDraft.getId());
messageDraftContent.setMessagedraft_content(content);
draftService.addMessageDraftContent(messageDraftContent);
//如果上传邮件附件非空
if(multipartFile!=null){
tip = saveAttachment(multipartFile, messageDraft.getId(), MessageAttachmentTargetTypeEnum.DAFT.getCode());
}
} catch (Exception e) {
txManager.rollback(status);//事务回滚
log.error("系统内部错误", e);
return HttpRespond.unknownException();
}
//如果上传附件类型有误
if (tip.equals("wrongFileType")) {
txManager.rollback(status);//事务回滚
return HttpRespond.wrongFileType();
}
//如果上传文件大小超过100M
if (tip.equals("wrongFileSize")) {
txManager.rollback(status);//事务回滚
return HttpRespond.wrongFileSize();
}
txManager.commit(status);//事务提交
return HttpRespond.success();
}
/**
* 修改草稿箱个人邮件
* @param jwt
* @param id
* @param title
* @param content
* @param multipartFile
* @param isChanged 是否发生修改标记
* @return
*/
@ApiOperation(value = "修改草稿箱个人邮件")
@PostMapping("/updateDraft")
@PreAuthorize("hasAnyAuthority('teacher_base','admin_base','student_base')")
public HttpRespond updateDraft(@RequestHeader("Authorization") String jwt,
@RequestParam(value = "id") Integer id,
@RequestParam(value = "title") String title,
@RequestParam(value = "content") String content,
@RequestParam(value = "multipartFile",required = false) MultipartFile multipartFile,
@RequestParam(value = "isChanged") Boolean isChanged) {
// 获取当前登录的用户信息: userId,
HashMap<String, String> userInfo = JsonInfoUtils.getUserInfo(jwt);
if (userInfo == null) {
return HttpRespond.unauthorized();
}
Integer userId = Integer.valueOf(userInfo.get("userId"));
// 开启事务管理
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus status = txManager.getTransaction(def);
String tip = "";
try {
//根据草稿id查询草稿箱信息
MessageDraft messageDraft = draftService.getById(id);
//封装数据
messageDraft.setUserId(userId);
messageDraft.setTitle(title);
//保存个人草稿
draftService.updateByIdAndUid(messageDraft);
//修改mongodb中的邮件草稿箱内容
draftService.updateMessageDraftContent(id,content);
//如果isChanged为false,附件不发生修改操作
//如果isChanged为true,附件发生修改操作
if(isChanged==true){
// 3,附件上传并插入 "附件" 数据
if(multipartFile!=null){
tip = updateAttachment(multipartFile, id);
}else{
//不存在上传附件,删除草稿箱邮件附件信息
attachmentService.deleteByTargetIdAndTargetType(id,MessageAttachmentTargetTypeEnum.DAFT.getCode());
}
}
} catch (Exception e) {
txManager.rollback(status);
log.error("系统内部错误", e);
return HttpRespond.unknownException();
}
txManager.commit(status);
//如果上传附件类型有误
if (tip.equals("wrongFileType")) {
return HttpRespond.wrongFileType();
}
//如果上传文件大小超过100M
if (tip.equals("wrongFileSize")) {
return HttpRespond.wrongFileSize();
}
return HttpRespond.success();
}
/**
* 查看某一邮件草稿具体信息
* @param jwt
* @param id
* @return
*/
@ApiOperation(value = "查看某一邮件草稿具体信息")
@GetMapping("/getOneDraft")
@PreAuthorize("hasAnyAuthority('teacher_base','admin_base','student_base')")
public HttpRespond getOneDraft(@RequestHeader("Authorization") String jwt,
@RequestParam(value = "id") Integer id){
// 获取当前登录的用户信息: userId,
HashMap<String, String> userInfo = JsonInfoUtils.getUserInfo(jwt);
if (userInfo == null) {
return HttpRespond.unauthorized();
}
Integer userId = Integer.valueOf(userInfo.get("userId"));
Map<String, Object> data = new HashMap<>();
//1。查询草稿箱邮件信息
MessageDraft messageDraft=draftService.getById(id);
//2.从mongodb查询邮件草稿内容
MessageDraftContent messageDraftContent=draftService.getMessageDraftContent(id);
messageDraft.setContent(messageDraftContent.getMessagedraft_content());
data.put("messageDraft",messageDraft);
// 3. 根据关联邮件id查询附件
MessageAttachment attachment = attachmentService
.getByTargetIdAndTargetType(messageDraft.getId(), MessageAttachmentTargetTypeEnum.DAFT.getCode());
data.put("attachment", attachment);
return HttpRespond.success(data);
}
/**
* 上传保存邮件附件
* 默认支持附件上传类型(jpg,png,jpeg,gif,txt,doc,docx,xls,xlsx,pdf,zip,rar)
* 默认上传文件大小(100m)
*/
// throws Exception
private String saveAttachment(MultipartFile multipartFile, int targetId, int targetType) {
// 附件上传并插入 "附件" 数据
//获取上传的原始文件全称
String fileOriName = multipartFile.getOriginalFilename();
//获取上传的文件名称
String fileName = fileOriName.substring(0, fileOriName.lastIndexOf("."));
String type = "jpg,png,jpeg,gif,txt,doc,docx,xls,xlsx,pdf,zip,rar";
//获取上传文件的后缀名(文件类型)
String fileExt = fileOriName.substring(fileOriName.lastIndexOf(".") + 1);
//上传文件格式不符合
if (!type.contains(fileExt)) {
return "wrongFileType";
}
long length = multipartFile.getSize();
//获取上传文件大小
double fileSize = FileSizeUtil.getFileSize(length, "B");
//如果上传文件大小大于100m
if (fileSize / 1048576 > 100) {
return "wrongFileSize";
}
// String size = fileSize + "B";
String size = String.valueOf(fileSize);
String[] uploadResults = null;
byte[] fileBuff = null;
InputStream inputStream = null;
try {
//接受字符文件输入流
inputStream = multipartFile.getInputStream();
if (inputStream != null) {
//获取数据流中含有字节数
int len1 = inputStream.available();
fileBuff = new byte[len1];
//从(来源)输入流中(读取内容)读取的一定数量字节数,并将它们存储到(去处)缓冲区数组fileBuff中
inputStream.read(fileBuff);
}
} catch (IOException e) {
log.error("IO Exception : add file exception!", e);
} finally {
try {
inputStream.close();
} catch (IOException e) {
log.error("IO Exception : close Input Stream error!", e);
}
}
//上传文件,返回所属组别以及远程文件名称
uploadResults = FastDFSClient.upload(fileName, fileExt, fileBuff);
String groupName = uploadResults[0];
String remoteName = uploadResults[1];
String url = null;
try {
//得到上传后远程文件的访问路径
url = FastDFSClient.getFilePath(groupName, remoteName);
} catch (IOException e) {
log.error("IO Exception : close Input Stream error!", e);
}
//封装数据
MessageAttachment attachment = new MessageAttachment();
attachment.setTargetId(targetId);
attachment.setTargetType(targetType);
attachment.setOriginalName(fileOriName);
attachment.setActualName(fileName);
attachment.setFileSize(size);
attachment.setFileUrl(url);
attachment.setFileType(fileExt);
attachmentService.save(attachment);
return "success";
}
/**
* 上传修改邮件附件
* 默认支持附件上传类型(jpg,png,jpeg,gif,txt,doc,docx,xls,xlsx,pdf,zip,rar)
* 默认上传文件大小(100m)
*/
private String updateAttachment(MultipartFile multipartFile, int targetId) {
// 3,附件上传并插入 "附件" 数据
//获取上传的原始文件全称
String fileOriName = multipartFile.getOriginalFilename();
//获取上传的文件名称
String fileName = fileOriName.substring(0, fileOriName.lastIndexOf("."));
String type = "jpg,png,jpeg,gif,txt,doc,docx,xls,xlsx,pdf,zip,rar";
//获取上传文件的后缀名(文件类型)
String fileExt = fileOriName.substring(fileOriName.lastIndexOf(".") + 1);
//上传文件格式不符合
if (!type.contains(fileExt)) {
return "wrongFileType";
}
long length = multipartFile.getSize();
//获取上传文件大小
double fileSize = FileSizeUtil.getFileSize(length, "B");
//如果上传文件大小大于100m
if (fileSize / 1048576 > 100) {
return "wrongFileSize";
}
// String size = fileSize + "B";
String size = String.valueOf(fileSize);
String[] uploadResults = null;
byte[] fileBuff = null;
InputStream inputStream = null;
try {
//接受字符文件输入流
inputStream = multipartFile.getInputStream();
if (inputStream != null) {
//获取数据流中含有字节数
int len1 = inputStream.available();
fileBuff = new byte[len1];
//从(来源)输入流中(读取内容)读取的一定数量字节数,并将它们存储到(去处)缓冲区数组fileBuff中
inputStream.read(fileBuff);
}
} catch (IOException e) {
log.error("IO Exception : add file exception!", e);
} finally {
try {
inputStream.close();
} catch (IOException e) {
log.error("IO Exception : close Input Stream error!", e);
}
}
//上传文件,返回所属组别以及远程文件名称
uploadResults = FastDFSClient.upload(fileName, fileExt, fileBuff);
String groupName = uploadResults[0];
String remoteName = uploadResults[1];
String url = null;
try {
//得到上传后远程文件的访问路径
url = FastDFSClient.getFilePath(groupName, remoteName);
} catch (IOException e) {
log.error("IO Exception : close Input Stream error!", e);
}
//根据草稿箱id查找附件信息
MessageAttachment attachment = attachmentService.getByTargetId(targetId,MessageAttachmentTargetTypeEnum.DAFT.getCode());
//若查找邮件信息不为空,则进行修改操作
if(attachment!=null){
//封装数据
attachment.setOriginalName(fileOriName);
attachment.setActualName(fileName);
attachment.setFileSize(size);
attachment.setFileUrl(url);
attachment.setFileType(fileExt);
attachment.setDeleted(false);
attachmentService.update(attachment);
}else{
//若没有则进行新增操作
//新增实体类封装
MessageAttachment attachmentInfo=new MessageAttachment();
attachmentInfo.setTargetType(MessageAttachmentTargetTypeEnum.DAFT.getCode());
attachmentInfo.setTargetId(targetId);
attachmentInfo.setOriginalName(fileOriName);
attachmentInfo.setActualName(fileName);
attachmentInfo.setFileSize(size);
attachmentInfo.setFileUrl(url);
attachmentInfo.setFileType(fileExt);
attachmentInfo.setDeleted(false);
attachmentService.save(attachmentInfo);
}
return "success";
}
这里常见的是上传一些图片以及文件,以提交表单方式传递文件流到后台,后台处理后上传到图片服务器,比如fastDFS文件服务器,将该文件的信息再存储到数据库中,再进行多张表数据的绑定。
主要用到的方法有:
1.上传文件时做个数限制的方法:
2.上传文件时做类型控制的方法:
3.文件状态发生改变,拿到前端文件流数据:
这里主要是通过upload控件进行一个回显,然后可以修改上传的附件。
主要用到的方法有:
1.附件回显,使用它的file-list属性,接收name和url即可:
标签默认是以action属性单独提交文件到服务器中,如果需要以提交表单的方式来提交文件流数据,就要用http-request属性去自定义上传文件的方法,这样就会调用http-request声明的方法,而不会走action声明的方法。这里我是以提交表单的方式来提交文件流数据,所以就自定义了一个方法upload来进行模拟上传,里面没有写什么具体的实现,因为我是最后提交表单时才将该文件流数据上传到服务器。
主要用到的方法有: