- springboot实现图片上传到又拍云中,外连接也可访问图片前提准备请见springboot实现图片上传到又拍云中,外连接也可访问图片(一)
- 主要代码讲解
@PostMapping("/uploadImg")
public Result uploadImg(MultipartFile file,Integer userId) throws IOException, UpException {
UpYun upYun = new UpYun("job-imags", "dream", "GoANPm05VpUcsl4MpG9fL4PFVSBoxdH3");
String filename = file.getOriginalFilename()+UUID.randomUUID().toString()+".jpg";
System.out.println("图片名称:"+filename);
boolean re = upYun.writeFile(filename,file.getBytes(),false);
Integer a=usersService.addImgPath("http://job-imags.test.upcdn.net/"+filename,userId);
return Result.success(re);
}
- [1] Upyun是又拍云的jar,引入即可。
- [2]UpYun(参数1,参数2,参数3)方法传递到三个参数,参数1:你创建的服务名称;参数二:你创建的操作员名称;参数三:你创建操作员生成的密码。
UpYun upYun = new UpYun("job-imags", "dream", "GoANPm05VpUcsl4MpG9fL4PFVSBoxdH3");
- [3] fileName是图片名字,为了防止图片名字重复造成的图片覆盖问题,使用UUID生成。图片名字后缀写死.的.jpg格式。想要任何格式可以解析上传文件的后缀。这个自行百度。
String filename = file.getOriginalFilename()+UUID.randomUUID().toString()+".jpg";
- [4] 上传的关键,就一行代码,upYun.writeFile(参数1,参数2,参数3)返回布尔类型,参数1:图片名字;参数2:图片;参数3:是否能创建目录,true为可以,false为不可以。
boolean re = upYun.writeFile(filename,file.getBytes(),false);