七牛云文件上传
1、引入Maven依赖
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.7.0, 7.7.99]</version>
</dependency>
2、配置yaml文件
qiniu:
accessKey: 2mz0xTvAym2AzqMZjRARPSRDYtxO3NLbaJV6Lakw
secretKey: _UBkk3q2VNzSUjIbogJggp2klvhb9X_4VUvrj5YJ
bucketName: ken-chy-blog
path: http://cdn.ken-chy129.cn
公钥与私钥可以到密钥管理处查看
bucket为创建的对象存储的空间名称
path为文件管理中的外链域名(默认使用七牛云测试域名)
3、编写对应配置类
@org.springframework.context.annotation.Configuration
public class UploadConfig {
@Value("${qiniu.accessKey}")
private String accessKey;
@Value("${qiniu.secretKey}")
private String secretKey;
@Bean
public Auth getAuth(){
return Auth.create(accessKey,secretKey);
}
@Bean
public UploadManager getUploadManager(){
return new UploadManager(new Configuration());
}
}
其中Auth.create()传入公钥私钥以创建权限,供UploadManager上传文件时使用
4、编写七牛云工具类
@Component
public class QiniuUtils {
@Autowired
private UploadManager uploadManager;
@Autowired
private Auth auth;
@Value("${qiniu.bucketName}")
private String bucketName;
@Value("${qiniu.path}")
private String url;
public String upload(FileInputStream file, String fileName) throws QiniuException {
String token = auth.uploadToken(bucketName);
Response res = uploadManager.put(file, fileName, token, null, null);
if (!res.isOK()) {
throw new RuntimeException("上传七牛云出错:" + res);
}
return url+"/"+fileName;
}
}
创建StringUtils工具类以生成图片名称
public class StringUtils {
public static String getRandomImgName(String fileName) {
int index = fileName.lastIndexOf(".");
if (fileName.isEmpty() || index == -1){
throw new IllegalArgumentException();
}
String suffix = fileName.substring(index).toLowerCase();
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
return "userAvatar:" + uuid + suffix;
}
}
5、编写Service层
@Service
public class PictureServiceImpl implements PictureService {
@Autowired
private QiniuUtils qiniuUtils;
@Override
public Result<String> upload(MultipartFile file) {
if (file.isEmpty()) {
return new Result<String>().failed(StatusCode.PICTURE_NULL);
}
String fileName = StringUtils.getRandomImgName(Objects.requireNonNull(file.getOriginalFilename()));
try {
FileInputStream uploadFile = (FileInputStream) file.getInputStream();
String path = qiniuUtils.upload(uploadFile, fileName);
return new Result<String>().success(path);
} catch (IOException e) {
e.printStackTrace();
return new Result<String>().failed(StatusCode.ERROR);
}
}
}
6、编写controller层
@RestController
@CrossOrigin
public class PictureController {
@Autowired
private PictureService pictureService;
@PostMapping(value = "/upload")
public Result<String> upload(@RequestParam("file") MultipartFile file) {
return pictureService.upload(file);
}
}
|