带有图片的模块相关代码,自己记录一下
页面代码
定义参数
return {
upload_url: '',//上传URL
upload_name: '',//图片或视频名称
ad_url: '',//上传后的图片或视频URL
ad_url_list: [],//预览列表
}
js相关方法
handleExceed: function () {
this.$message.error('请先删除选择的图片,再上传!');
},
handleRemove: function (res, file) {
var self = this;
self.ad_url = '';
var liItem = document.getElementsByClassName('hide-video-box')[0];
liItem.innerHTML = '';
},
uploadSectionFile: function (params) {
var self = this,
file = params.file,
fileType = file.type,
isImage = fileType.indexOf('image') != -1,
isVideo = fileType.indexOf('video') != -1,
file_url = self.$refs.upload.uploadFiles[0].url;
var isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
this.$message.error('上传图片大小不能超过 2MB!');
self.$refs.upload.uploadFiles = [];
return;
}
if(!isImage && !isVideo){
this.$message.error('请选择图片!');
self.$refs.upload.uploadFiles = [];
return;
}
if (isImage) {
var img = new Image();
img.src = file_url;
img.onload = function () {
//图片上传
self.upload_url = `/school/paper/upload`;
self.upload_name = file.name;
self.uploadFile(file, isVideo, '');
}
// } else if (isVideo) {
// var isMP4 = file.type === 'video/mp4';
// if (!isMP4) {
// _.$alert('上传视频只支持 mp4 格式!', '提示', { type: 'error' });
// self.$refs.upload.uploadFiles = [];
// return;
// }
// var videoDiv = document.createElement('video');
// var liItem = document.getElementsByClassName('hide-video-box')[0];
// videoDiv.src = file_url;
// liItem.appendChild(videoDiv);
// videoDiv.onloadeddata = function (event) {
// var target = event.target;
// var width = target.offsetWidth;
// var height = target.offsetHeight;
// if (width !== 750 || height != 1125) {
// _.$alert('视频尺寸为750*1125px', '提示', { type: 'error' });
// //将上传列表清空
// self.$refs.upload.uploadFiles = [];
// return;
// }
// //视频上传
// self.upload_url = '你的视频上传URL';
// self.upload_name = 'file_video[]';
// self.uploadFile(file, isVideo, videoDiv);
// }
}
},
uploadFile: function (file, isVideo, videoDiv) {
var self = this
let fileFormData = new FormData();
fileFormData.append('file', file,self.upload_name);//upload_name是键,file是值,就是要传的文件,test.zip是要传的文件名
let requestConfig = {
headers: {
'Content-Type': 'multipart/form-data'
},
}
this.$http.post(this.$http.adornUrl(self.upload_url),fileFormData,requestConfig).then(({data}) => {
if (data && data.code === 0) {
self.ad_url = data.url;
this.dataForm.quesPic = data.url;
//创建一个显示video的容器
// if (isVideo) {
// var liItem = document.getElementsByClassName('el-upload-list__item')[0];
// videoDiv.style.width = '278px';
// videoDiv.style.height = '415px';
// liItem.prepend(videoDiv);
// }
return;
}
this.$message.error('上传失败,请重新上传!');
self.$refs.upload.uploadFiles = [];
})
},
表单提交
// 表单提交
dataFormSubmit () {
this.$refs['dataForm'].validate((valid) => {
if (valid) {
this.$http({
url: this.$http.adornUrl(`/school/paper/${!this.dataForm.id ? 'save' : 'update'}`),
method: 'post',
data: this.$http.adornData({
'id': this.dataForm.id || undefined,
'questions': this.dataForm.questions,
'answer1': this.dataForm.answer1,
'answer2': this.dataForm.answer2,
'answer3': this.dataForm.answer3,
'answer4': this.dataForm.answer4,
'trueanswer': this.dataForm.trueanswer,
'type': this.dataForm.type,
'explain': this.dataForm.explain,
'num': this.dataForm.num,
'quesPic':this.dataForm.quesPic
})
}).then(({data}) => {
if (data && data.code === 0) {
this.$message({
message: '操作成功',
type: 'success',
duration: 1500,
onClose: () => {
this.visible = false
this.$emit('refreshDataList')
}
})
} else {
this.$message.error(data.msg)
}
})
}
})
}
yml自定义图片存储路径
# 自定义配置
img:
imgpath: static/images/upload/
代码读取yml配置参数
@Value("${img.imgpath}")
private String imgPath;
上传图片方法
/**
* 上传图片
*/
@SysLog("上传图片")
@PostMapping("/upload")
//@RequiresPermissions("school:paper:import")
public R uploadPic(@RequestParam("file") MultipartFile multipartFile) {
File targetFile=null;
String url="";//返回存储路径
if (multipartFile.isEmpty()) {
throw new RRException("上传图片不能为空");
}
if (multipartFile.getContentType().contains("image")) {
try{
String fileName = multipartFile.getOriginalFilename();
String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
if(StringUtils.isNotBlank(fileName)){
fileName=new Date().getTime()+"_"+new Random().nextInt(1000) + fileF;//新的文件名
// File file = new File(imgPath);
Resource resource = new ClassPathResource("static");
File file = new File(imgPath);
// 输出文件夹绝对路径 -- 这里的绝对路径是相当于当前项目的路径而不是“容器”路径
System.out.println(file.getAbsolutePath());
//判断文件夹是否存在
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
//将图片存入文件夹
//"src/main/resources/" +
targetFile = new File(file.getAbsolutePath()+ File.separator + fileName);
multipartFile.transferTo(targetFile);
url=imgPath+fileName;
}
return R.ok().put("url",url);
} catch (Exception e) {
e.printStackTrace();
return R.error("上传失败");
}
}else{
throw new RRException("上传图片格式不正确");
}
}
需要注意的是使用multipartFile.transferTo(targetFile);
方法时targetFile
需要是绝对路径
列表页面图片回显
页面代码:
js处理:
// 获取数据列表
getDataList () {
this.dataListLoading = true
this.$http({
url: this.$http.adornUrl('/school/paper/list'),
method: 'get',
params: this.$http.adornParams({
'page': this.pageIndex,
'limit': this.pageSize,
'key': this.dataForm.key
})
}).then(({data}) => {
if (data && data.code === 0) {
this.dataList = data.page.list
for (const obj of this.dataList) {
if(obj.quesPic){
obj.quesPic = "http://ip:端口/projectName/"+obj.quesPic
}
}
this.totalPage = data.page.totalCount
} else {
this.dataList = []
this.totalPage = 0
}
this.dataListLoading = false
})
},
编辑图片回显:
init (id) {
this.ad_url_list = []
this.dataForm.id = id || 0
this.visible = true
this.$nextTick(() => {
this.$refs['dataForm'].resetFields()
if (this.dataForm.id) {
this.$http({
url: this.$http.adornUrl(`/school/paper/info/${this.dataForm.id}`),
method: 'get',
params: this.$http.adornParams()
}).then(({data}) => {
if (data && data.code === 0) {
this.dataForm.questions = data.paper.questions
this.dataForm.answer1 = data.paper.answer1
this.dataForm.answer2 = data.paper.answer2
this.dataForm.answer3 = data.paper.answer3
this.dataForm.answer4 = data.paper.answer4
this.dataForm.trueanswer = data.paper.trueanswer
this.dataForm.type = data.paper.type
this.dataForm.explain = data.paper.explain
this.dataForm.num = data.paper.num,
this.dataForm.quesPic = data.paper.quesPic
}
if(data.paper.quesPic){
this.ad_url_list.push({
'url':" http://ip:端口/projectName/"+data.paper.quesPic,
"name":data.paper.quesPic
})
}
})
}
})
},