springboot+vue+element-ui实现图文上传(表单文字和图片一起入库)
前端页面:<el-dialog title="添加图文" :visible.sync="dialogVisible"><el-form :model="configForm" ref="configForm" label-width="100px":rules="rules"v-loadi...
·
前端页面:
<el-dialog title="添加图文" :visible.sync="dialogVisible">
<el-form :model="configForm" ref="configForm" label-width="100px"
:rules="rules"
v-loading="loading2">
<h3 class="title modal-headline">添加图文</h3>
<el-form-item label=" 图文标题" prop="imgTitle">
<el-input v-model="configForm.imgTitle"
type="text"
auto-complete="off" placeholder="请输入标题"></el-input>
</el-form-item>
<el-form-item label="添加文字" prop="imgText">
<el-input v-model="configForm.imgText"
type="textarea"
auto-complete="off" placeholder="请输入文字内容"></el-input>
</el-form-item>
<el-form-item label="添加图片" ref="uploadElement" prop="img">
<el-input v-model="configForm.img" v-if="false"></el-input>
<el-upload
class="upload-demo"
:on-success="handleAvatarSuccess"//这里是后台的回调信息
accept="image/jpeg,image/jpg,image/png"//控制类型
:action="materialPictureAndText()"//后台方法
:auto-upload="false"//关闭自动上传
:before-upload="beforeUpload2"//文件控制
ref="upload"
:on-change="handleChange"//文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
multiple
:data="configForm"> //表单数据
<el-button type="success" size="small">选择文件</el-button>
</el-upload>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary"
@click="submitImg('configForm')" >确 定</el-button>
<el-button @click="dialogVisible = false">取 消</el-button>
</div>
</el-dialog>
js:
submitImg (forName) {
let self = this
this.$confirm('此操作将无法撤回, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
self.$refs[forName].validate((valid) => {
if (valid) {
self.$refs.upload.submit()
self.dialogVisible = false
self.loading2 = false
} else {
return false
}
})
}).catch(() => {
this.$message({
type: 'info',
message: '已取消更新'
})
})
},
handleAvatarSuccess (response, file) {
let self = this
let resp = response
console.log(response)
if (resp.result === 200) {
setTimeout(() => {
self.dialogVisible = false//关闭弹窗
self.$refs.upload.clearFiles()
self.$message.success(resp.msg)//显示后台信息
self.getImgData()//上传后刷新表单
}, 1000)
} else {
self.$message.error(resp.msg)//显示后台信息
self.$refs.upload.clearFiles()//清空表单
}
},
materialPictureAndText () {
return Config.context + '/pictureManage/materialPicture' //前面是为了方便线上加的
},
beforeUpload2 (file) {
const isLt2M = file.size < 1024 * 1024 * 2
// console.log('大小' + isLt2M)
if (!isLt2M) {
this.$message.error('上传文件大小不能超过 2MB!')
}
let size = file.size / 1024
console.log('大小' + size)
let _URL = window.URL || window.webkitURL
let img = new Image()
img.onload = function () {
let width = img.width
let height = img.height
console.log('width--->' + width)
console.log('height--->' + height)
}
img.src = _URL.createObjectURL(file)
return isLt2M
},
后台控制层:
@PostMapping(value = "materialPicture", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Map<String, Object> materialPictureAndText(HttpServletRequest request,
@RequestParam(value = "imgTitle", required = false) String imgTitle,
@RequestParam(value = "file", required = false) MultipartFile file) {
if (file.isEmpty()) {
HashMap<String, Object> resultMap = new HashMap<>();
resultMap.put("msg", "请上传图片");
return resultMap;
} else {
String fileName = file.getOriginalFilename(); // 文件名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
String filePath = path;//这个path就是你要存在服务器上的
fileName = UUID.randomUUID() + suffixName; // 新文件名
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
}
Picture materialPicture = new Picture();
materialPicture.setImgTitle(imgTitle);
String filename = apiUrl + fileName;
materialPicture.setPicture_url(filename);
return pictureService.imgUpload(materialPicture);//这里就是上传图片返回的信息,成功失败异常等,前端根据字段接收就是了
}
}
关于图片的显示,我是用了tomcat服务器,应该用其他也一样的,在代码里配置映射路径
先在配置文件中:
在写一个配置文件配置映射路径,然后在tomcat下面跑即可:
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
@Value("${file.staticAccessPath}")
private String staticAccessPath;
@Value("${file.uploadFolder}")
private String uploadFolder;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + uploadFolder);
WebMvcConfigurer.super.addResourceHandlers(registry);
}
}
更多推荐
已为社区贡献8条内容
所有评论(0)