Java后端实现七牛云上传图片、读取图片链接
添加依赖
<!--七牛云sdk-->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.2.11</version>
</dependency>
controller
@Api("文件上传")
@RestController
public class UploadController {
@Autowired
private UploadService uploadService;
@PostMapping(path = "/avatar",produces = "application/json")
@ApiOperation("更换头像")
public ResModel replaceAvator(@ApiParam("头像文件") MultipartFile file) throws IOException {
return uploadService.replaceAvatar(file);
}
}
service接口
public interface UploadService {
ResModel replaceAvatar(MultipartFile file);
}
serivce实现类
@Service
public class UploadServiceImpl implements UploadService {
@Override
public ResModel replaceAvatar(MultipartFile file) {
try {
Configuration config = new Configuration(Zone.zone0());
UploadManager manager = new UploadManager(config);
String accessKey="XXX";
String secretKey="XXX";
String bucket="XXX";
Auth auth = Auth.create(accessKey, secretKey);
String token = auth.uploadToken(bucket);
Response response = manager.put(file.getInputStream(), file.getOriginalFilename(), token, null, null);
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);
System.out.println(putRet.hash);
String path = getFilePath(putRet.key);
System.out.println(path);
return path;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String getFilePath(String fileName) {
String publicUrl = "XXX"+ fileName;
return publicUrl;
}
}
前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
//action,修改后端接口路径
<form action="http://localhost:8089/avatar" method="post" enctype="multipart/form-data">
选择需要上传的文件:<input type="file" name="file">
<input type="submit" value="提交">
</form>
</body>