需求:
点击操作按钮,选择上传,弹出上传dialog,使用upload组件实现图片上传,并可在前端进行预览
先看上传
前端实现:
弹出框:
<el-dialog
:title="titleFlag"
:visible.sync="uploadFlag"
width="30%"
:close-on-click-modal="false"
class="uploadFlag"
@close="()=>{this.fileListDate=[];this.uploadFlag = false}"
>
<div
v-loading="loading"
element-loading-text="拼命上传中"
element-loading-spinner="el-icon-loading"
>
<span>温馨提示:该类型为重要材料,上传重要材料可降低用工风险</span>
<div style="margin-top: 20px;">
<el-form>
<el-form-item>
<el-upload
ref="upload"
class="upload-demo"
drag
:http-request="uploadAvatar"
:on-remove="handleRemove"
:file-list="fileListDate"
:before-upload="beforeAvatarUpload"
action="#"
:limit="1"
:on-exceed="handleExceed"
accept=".jpg,.jpeg,.png,.doc,.docx,.pdf,.excel,.xlsx,.xls"
:on-progress="fileProgress"
>
<i class="el-icon-upload" />
<div>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div slot="tip" class="el-upload__tip">文件不超过10M</div>
</div>
</el-upload>
</el-form-item>
</el-form>
<!--<div slot="footer" class="dialog-footer">
<el-button @click="uploadFlag = false">取 消</el-button>
<el-button type="primary" @click="onSubmit()">确 定</el-button>
</div>-->
<div slot="footer" class="dialog-footer" style="text-align: right;">
<el-button @click="()=>{this.fileListDate=[];this.uploadFlag = false}">取 消</el-button>
<el-button type="primary" @click="onSubmit">确 定</el-button>
</div>
</div>
</div>
data中主要参数:
data(){
return{
// 存储时使用
photolData: {
userId: this.$route.params.userId,
materialType: '',
filePath: '',
dataType: '1'
},
// 图片列表
fileListDate: [],
// 预览时使用
imgList: [],
}
}
methods:
// 方法名
uploadAvatar(data) {
const formData = new FormData()
formData.append('avatarfile', data.file)
formData.append('userId', this.photolData.userId)
formData.append('materialType', this.photolData.materialType)
this.loading = true
// 后台接口
uploadAvatar(formData).then(response => {
this.fileListDate.push({ name: data.file.name, url: response.msg })
this.loading = false
})
},
js中定义后台接口:
// 上传材料附件
export function uploadAvatar(data) {
return request({
url: '/aa/bbb/avatar',
method: 'post',
data: data
})
}
// 保存上传图片
export function addPhoto(data) {
return request({
url: '/aaa/bbb/addPhotoInfo',
method: 'post',
data: data
})
}
// 预览个人证件照
export function previewPhoto(userId, materialType) {
return request({
url: '/aaa/bbb/previewPhotoByUserId?userId=' + userId + '&materialType=' + materialType,
method: 'get',
})
}
当前页面引用js中的方法
import {uploadAvatar,addPhoto,previewPhoto} from '@/api/aaa/bbb/xxx.js'
浏览器中的请求:
后台实现:
/**
* 上传图片
*
* @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.photolData.filePath = JSON.stringify(this.fileListDate)
if (this.photolData.filePath === '[]') {
return this.msgError('上传文件不能为空!')
}
// 调用接口
addPhoto(this.photolData).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("/addPhotoInfo")
public AjaxResult addPhotoInfo(@Validated @RequestBody Photo photo) {
photo.setCreateBy(getUsername());
List<UploadVo> uploadVo = JSONArray.parseArray(photo.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")) {
photo.setIsPic("0");
} else {
photo.setIsPic("1");
}
int i = photoService.insertPhotoInfo(photo);
String remark = "";
if (i > 0) {
for (int x = 0; x < fileType.length; x++) {
if (photo.getMaterialType().equals(fileType[x])) {
remark = "新增" + photo.getMaterialType();
operatorRecordService.insertOperarot(photo.getUserId(), remark);
return toAjax(i);
}
}
remark = "新增" + photo.getMaterialType();
operatorRecordService.insertOperarot(photo.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;
}
然后调用新增方法insertPhotoInfo入库:
入库成功
然后点击预览,进行查看
预览(轮播展示):
前端效果:
前端实现:
预览dialog
<!--证件预览-->
<el-dialog :title="previewTitle" :visible.sync="previewFlag" width="40%" :close-on-click-modal="false">
<el-carousel
indicator-position="none"
arrow="always"
:autoplay="false"
@change="((pre, next) => {imgChange(pre, next)})"
>
<el-carousel-item v-for="(item,index) in imgList" :key="index">
<div v-if="item.type==='0'" style="text-align: center;">
<img :src="item.url" style="height: 300px">
</div>
<div v-if="item.type==='1'" style="display: flex; justify-content: space-around; align-items: center; padding: 0 10%; height:100%;">
<el-image :src="require('@/assets/images/excel.png')" style="width: 220px;" />
<el-button type="primary" plain style="height:36px;" @click="down(item.url)">下载文档</el-button>
</div>
</el-carousel-item>
</el-carousel>
</el-dialog>
// 预览方法
previewFile(fileType) {
this.previewFlag = false
this.imgList = []
previewPhoto(this.photoData.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("/previewPhotoByUserId")
public AjaxResult previewPhotoByUserId(String userId, String materialType) {
List<Photo> photo= photoService.previewPhotoByUserId(userId, materialType);
String remark = "";
if (photo!= null) {
for (int x = 0; x < fileType.length; x++) {
if (materialType.equals(fileType[x])) {
remark = "预览了" + materialType;
operatorRecordService.insertOperarot(photo.get(0).getUserId(), remark);
return AjaxResult.success(photo);
}
}
}
return AjaxResult.success(photo);
}
xml中:
<select id="previewPhotoByUserId" parameterType="String" resultMap="BaseMaterialResult">
select id, user_id, material_type, file_path, is_pic
from photo
where user_id = #{userId}
and material_type = #{materialType}
and file_path !='[]'
</select>
接口返回的数据,主要看filePath
预览时需要给url添加前缀
最终展示(轮播展示的):
至此就完成了~,记录一下,仅供参考。
描述有误的地方欢迎大家指正,大家有问题可加qq 876942434。一起进步~