使用七牛云进行图片上传:
1.工具类QiniuUtils:
依赖
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.2.0</version>
</dependency>
/**
* 七牛云工具类
*/
public class QiniuUtils {
public static String accessKey = "***";
public static String secretKey = "***";
public static String bucket = "***";
public static void upload2Qiniu(String filePath, String fileName) {
//构造一个带指定Zone对象的配置类
Configuration cfg = new Configuration(Zone.zone2());
UploadManager uploadManager = new UploadManager(cfg);
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(filePath, fileName, upToken);
//解析上传成功的结果
DefaultPutRet putRet =
new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
} catch (QiniuException ex) {
Response r = ex.response;
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
}
}
//上传文件
public static void upload2Qiniu(byte[] bytes, String fileName) {
//构造一个带指定Zone对象的配置类
Configuration cfg = new Configuration(Zone.zone2());
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//默认不指定key的情况下,以文件内容的hash值作为文件名
String key = fileName;
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(bytes, key, upToken);
//解析上传成功的结果
DefaultPutRet putRet =
new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);
System.out.println(putRet.hash);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
}
}
//删除文件
public static void deleteFileFromQiniu(String fileName) {
//构造一个带指定Zone对象的配置类
Configuration cfg = new Configuration(Zone.zone2());
String key = fileName;
Auth auth = Auth.create(accessKey, secretKey);
BucketManager bucketManager = new BucketManager(auth, cfg);
try {
bucketManager.delete(bucket, key);
} catch (QiniuException ex) {
//如果遇到异常,说明删除失败
System.err.println(ex.code());
System.err.println(ex.response.toString());
}
}
}
注意:
这个地方需要根据自己创建存储空间选择的区域进行选择。
2.后端代码
3.controller:
@Api("七牛云图片上传")
@CrossOrigin
@RestController
@RequestMapping(value ="/edossservice/oss/file")
public class OssController {
@Autowired
private FileService fileService;
@ApiOperation("图片上传")
@PostMapping(value ="/uploadImage")
public R uploadImage(
@ApiParam(value = "文件",name = "file",required = true)
@RequestParam("file") MultipartFile file
){
return R.ok().data("url",fileService.upload(file));
}
}
应为使用的是SpringBoot+vue所以要设置@CrossOrigin注解,保证可以跨域成功。
service:
public interface FileService {
/**
* 文件上传至七牛云
* @param file
* @return
*/
String upload(MultipartFile file);
}
@Service
public class FileServiceImpl implements FileService {
@Override
public String upload(MultipartFile imgFile) {
System.out.println("upload..befor");
try {
//获取原始文件名
String originalFilename = imgFile.getOriginalFilename();
int lastIndexOf = originalFilename.lastIndexOf(".");
//获取文件后缀
String suffix = originalFilename.substring(lastIndexOf - 1);
//使用UUID随机产生文件名称,防止同名文件覆盖
String fileName = UUID.randomUUID().toString() + suffix;
QiniuUtils.upload2Qiniu(imgFile.getBytes(), fileName);
System.out.println("upload..after");
//将图片名称存入redis中
//图片上传成功
return "自己的地址"+fileName;
} catch (Exception e) {
e.printStackTrace();
//图片上传失败
return "";
}
}
}
4.前端代码
<!-- 课程封面-->
<el-form-item label="课程封面">
<el-upload
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
:action="BASE_API + '/edossservice/oss/file/uploadImage'"
class="avatar-uploader"
>
<img :src="courseInfo.cover" />
</el-upload>
</el-form-item>
//上传封面成功调用的方法
handleAvatarSuccess (res, file) {
this.courseInfo.cover = res.data.url
},
//上传之前调用的方法
beforeAvatarUpload (file) {
const isJPG = file.type === 'image/jpeg'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!')
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!')
}
return isJPG && isLt2M
},