需求:
点击操作按钮,选择上传,弹出上传dialog,使用upload组件实现图片上传,并可在前端进行预览
先看上传
前端实现:
弹出框:
{this.fileListDate=[];this.uploadFlag = false}"
>
温馨提示:该类型为重要材料,上传重要材料可降低用工风险
将文件拖到此处,或点击上传
文件不超过10M
data中主要参数:
data(){
return{
// 存储时使用
baseMetaailData: {
userId: this.$route.params.userId,
materialType: '',
filePath: '',
dataType: '1'
},
// 图片列表
fileListDate: [],
// 预览时使用
imgList: [],
}
}
methods:
// 方法名
uploadEnclosure(data) {
const formData = new FormData()
formData.append('avatarfile', data.file)
formData.append('userId', this.baseMetaailData.userId)
formData.append('materialType', this.baseMetaailData.materialType)
this.loading = true
// 后台接口
uploadEnclosure(formData).then(response => {
this.fileListDate.push({ name: data.file.name, url: response.msg })
this.loading = false
})
},
js中定义后台接口:
// 上传材料附件
export function uploadEnclosure(data) {
return request({
url: '/feishu/membership/avatar',
method: 'post',
data: data
})
}
// 保存上传图片
export function addPersonalIdPhoto(data) {
return request({
url: '/feishu/membership/addPersonalIdPhoto',
method: 'post',
data: data
})
}
// 预览个人证件照
export function previewPersonalIdPhotoByUserId(userId, materialType) {
return request({
url: '/feishu/membership/previewPersonalIdPhotoByUserId?userId=' + userId + '&materialType=' + materialType,
method: 'get',
})
}
当前页面引用js中的方法
import {uploadEnclosure,addPersonalIdPhoto,previewPersonalIdPhotoByUserId} from '@/api/feishu/membership/memberInfo'
/**
* 上传材料附件
*
* @param file
* @return
* @throws IOException
*/
@PostMapping("/avatar")
public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file, String userId, String materialType) throws IOException {
if (!file.isEmpty()) {
String name = file.getOriginalFilename();
String avatar = "";
if (name.endsWith("jpg") || name.endsWith("jpeg") || name.endsWith("png")) {
avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
} else {
avatar = FileUploadUtils.upload(RuoYiConfig.getDownloadPath(), file);
}
String remark = "";
if (avatar != null) {
for (int x = 0; x < fileType.length; x++) {
if (materialType.equals(fileType[x])) {
remark = "上传了" + materialType;
operatorRecordService.insertOperarot(userId, remark);
return AjaxResult.success(avatar);
}
}
remark = "上传了" + materialType + "失败";
operatorRecordService.insertOperarot(userId, remark);
return AjaxResult.success(avatar);
}
return AjaxResult.success(avatar);
}
return AjaxResult.error("上传图片异常,请联系管理员");
}
工具类:FileUploadUtils
/**
* 根据文件路径上传
*
* @param baseDir 相对应用的基目录
* @param file 上传的文件
* @return 文件名称
* @throws IOException
*/
public static final String upload(String baseDir, MultipartFile file) throws IOException {
try {
return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
} catch (Exception e) {
throw new IOException(e.getMessage(), e);
}
}
获取图片路径,使用如若依框架自带的:RuoYiConfig
/**
* 获取头像上传路径
*/
public static String getAvatarPath()
{
return getProfile() + "/avatar";
}
上传成功后返回路径:
前端展示:
接下来就是将路径保存到数据库,然后前端页面点击预览,查看上传的图片:
methods中的submit方法:
onSubmit() {
this.baseMetaailData.filePath = JSON.stringify(this.fileListDate)
if (this.baseMetaailData.filePath === '[]') {
return this.msgError('上传文件不能为空!')
}
// 调用接口
addPersonalIdPhoto(this.baseMetaailData).then(resp => {
if (resp.code === 200) {
this.msgSuccess('提交成功')
this.getInitData()
this.uploadFlag = false
}
})
},
// 材料常量(随意写的)
public static final String[] fileType = {"照片", "照片2","照片3","照片4","照片5","照片6","照片7","照片8"};
@PostMapping("/addPersonalIdPhoto")
public AjaxResult addPersonalIdPhoto(@Validated @RequestBody BaseMaterial baseMaterial) {
baseMaterial.setCreateBy(getUsername());
List uploadVo = JSONArray.parseArray(baseMaterial.getFilePath()).toJavaList(UploadVo.class);
String urlName = "";
if (StringUtils.isNotNull(uploadVo) && uploadVo.size() > 0) {
urlName = uploadVo.get(0).getName();
}
//
if (urlName.endsWith("jpg") || urlName.endsWith("jpeg") || urlName.endsWith("png")) {
baseMaterial.setIsPic("0");
} else {
baseMaterial.setIsPic("1");
}
int i = baseMaterialService.insertBaseMaterialInfo(baseMaterial);
String remark = "";
if (i > 0) {
for (int x = 0; x < fileType.length; x++) {
if (baseMaterial.getMaterialType().equals(fileType[x])) {
remark = "新增" + baseMaterial.getMaterialType();
operatorRecordService.insertOperarot(baseMaterial.getUserId(), remark);
return toAjax(i);
}
}
remark = "新增" + baseMaterial.getMaterialType();
operatorRecordService.insertOperarot(baseMaterial.getUserId(), remark);
return toAjax(i);
}
return toAjax(i);
}
UploadVo :主要用于将filePath中的信息存储起来
public class UploadVo {
private Long uid;
private String name;
private String url;
private String success;
}
然后调用新增方法insertBaseMaterialInfo入库:
入库成功
然后点击预览,进行查看
预览(轮播展示):
前端效果:
前端实现:
预览dialog
{imgChange(pre, next)})"
>
下载文档
// 预览方法
previewFile(fileType) {
this.previewFlag = false
this.imgList = []
previewPersonalIdPhotoByUserId(this.baseMetaailData.userId, fileType).then(resp => {
if (resp.code === 200) {
if (resp.data) {
this.previewFlag = true
for (let i = 0; i < resp.data.length; i++) {
this.imgList.push({ type: resp.data[i].isPic, url: process.env.VUE_APP_BASE_API + JSON.parse(resp.data[i].filePath)[0].url })
}
} else {
this.$message.warning('暂无数据,请先上传')
}
}
})
},
后台:就是根据userId和证件类型去查询
/**
* 预览个人证件照
*
* @param userId
* @return
*/
@GetMapping("/previewPersonalIdPhotoByUserId")
public AjaxResult previewPersonalIdPhotoByUserId(String userId, String materialType) {
List baseMaterial = baseMaterialService.previewPersonalIdPhotoByUserId(userId, materialType);
String remark = "";
if (baseMaterial != null) {
for (int x = 0; x < fileType.length; x++) {
if (materialType.equals(fileType[x])) {
remark = "预览了" + materialType;
operatorRecordService.insertOperarot(baseMaterial.get(0).getUserId(), remark);
return AjaxResult.success(baseMaterial);
}
}
}
return AjaxResult.success(baseMaterial);
}
xml中:
预览时需要给url添加前缀
最终展示(轮播展示的):
至此就完成了~,记录一下,仅供参考,欢迎大家指正。
上述是个人理解。描述不恰当的地方欢迎指正,有问题可加qq 876942434,一起进步~