1.在webStorm的组件上使用头像上传标签
2.在ider写入OSS工具类
3.在Controller写一个post接口
4.头像上传成功执行element的方法
1.在webStorm的组件上使用头像上传标签
<el-form-item label="头像"> <el-upload class="avatar-uploader" action="http://192.16.6.666:7000/upload/upload" <!--接口--> :show-file-list="false" :on-success="handleAvatarSuccess2" <!--头像上传成功执行的方法--> > <img v-if="insertcaidan.menuImg" :src="insertcaidan.menuImg" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </el-form-item>
2.在ider写入OSS工具类
public class OSSUtils { public static String upload(MultipartFile file){ // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 String endpoint = "oss-cn-hangzhou.aliyuncs.com"; // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。 String accessKeyId = "***"; String accessKeySecret = "***"; // 填写Bucket名称,例如examplebucket。 String bucketName = "aaa998"; // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。 Calendar calendar = Calendar.getInstance(); String day = calendar.get(Calendar.YEAR)+"/"+(calendar.get(Calendar.MONTH)+1)+"/"+calendar.get(Calendar.DATE)+"/"; String objectName =day+ UUID.randomUUID().toString().replace("-","")+file.getOriginalFilename(); // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); try { InputStream inputStream =file.getInputStream(); // 创建PutObject请求。 ossClient.putObject(bucketName, objectName, inputStream); } catch (Exception e){ e.printStackTrace(); } finally { if (ossClient != null) { ossClient.shutdown(); } } String url = "https://"+bucketName+"."+endpoint+"/"+objectName; return url; } }
3.在Controller写一个post接口
@RestController @RequestMapping("/upload") public class UploadController { @PostMapping("/upload") public CommonResult upload(MultipartFile file){ String path= OSSUtils.upload(file); return new CommonResult(2000,"上传成功",path);//path是图片的地址 } }
4.头像上传成功执行element的方法
handleAvatarSuccess2(res, file) { this.insertcaidan.menuImg = res.data; //data是path的图片地址 },