文件上传组件
<template>
<div>
<el-upload
class="avatar-uploader"
action="/system/image"
:show-file-list="false"
:on-success="handleSuccess"
:before-upload="beforeUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</div>
</template>
<script>
export default {
data() {
return {
imageUrl: ''
}
},
methods: {
handleSuccess(response) {
this.imageUrl = response.data;
},
beforeUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isPNG = file.type === 'image/png';
if (!isJPG && !isPNG) {
this.$message.error('上传头像图片只能是 JPG 格式或 PNG 格式!');
return false;
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
return false;
}
return true;
}
}
}
</script>
在后端控制器中接收上传的图片并将其保存到服务器指定的目录下,
@Controller
@RequestMapping("/system")
public class SysImageController extends BaseController
{
@Value("${ruoyi.profile}")
private String uploadPath;
@PostMapping("/image")
@ResponseBody
public AjaxResult uploadImage(MultipartFile file) throws IOException
{
if (!file.isEmpty())
{
// 保存图片到服务器指定的目录下
String fileName = FileUtils.upload(uploadPath, file);
String url = "/profile/" + fileName;
AjaxResult ajax = AjaxResult.success();
ajax.put("data", url);
return ajax;
}
return AjaxResult.error("上传图片失败!");
}
}
在前端页面上显示上传的图片
<template>
<div>
<img :src="imageUrl">
</div>
</template>
<script>
export default {
data() {
return {
imageUrl: ''
}
},
mounted() {
this.loadImage();
},
methods: {
loadImage() {
// 根据图片路径从服务器加载图片
this.imageUrl = '/system/image/xxx.jpg';
}
}
}
</script>
该文章展示了一个使用Vue.js实现的文件上传组件,限制上传图片为JPG或PNG格式且大小不超过2MB。成功上传后,图片会被保存到服务器指定目录,并返回URL给前端显示。后端使用控制器接收图片,保存到服务器,并返回图片URL。
9727

被折叠的 条评论
为什么被折叠?



