效果展示:
前端代码展示:
- action:后端api,/dev-api 的作用是一个标识,用来给webpack重写成相对应的地址。
<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
<el-form ref="form" :model="form" :rules="rules" label-width="100px">
<el-form-item label="证明材料" prop="mainImage">
<el-upload
class="avatar-uploader"
action="/dev-api/clock-in/qingjia/upload"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
</el-form>
</el-dialog>
data数据展示:
open: false,
imageUrl: '',
rules: {
userName: [
{ required: true, message: "角色名称不能为空", trigger: "blur" },
],
},
methods展示:
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
this.form.qjImage = file.response.fileName;
},
beforeAvatarUpload(file) {
const isLt5M = file.size / 1024 / 1024 < 5;
if (!isLt5M) {
this.$message.error('上传头像图片大小不能超过 5MB!');
}
return isLt5M;
},
后端代码:(若依自带的代码,源码在若依common包下)
@RestController
@RequestMapping("/clock-in/qingjia")
public class HJZT_QingjiaController extends BaseController {
@Autowired
private ServerConfig serverConfig;
@Anonymous
@PostMapping("/upload")
public AjaxResult uploadFile(MultipartFile file) throws Exception
{
try
{
// 上传文件路径
String filePath = HjZtConfig.getUploadPath();
String fileName = FileUploadUtils.upload(filePath, file);
String url = serverConfig.getUrl() + fileName;
AjaxResult ajax = AjaxResult.success();
ajax.put("url", url);
ajax.put("fileName", fileName);
ajax.put("newFileName", FileUtils.getName(fileName));
ajax.put("originalFilename", file.getOriginalFilename());
return ajax;
}
catch (Exception e)
{
return AjaxResult.error(e.getMessage());
}
}
}