引入依赖
<!--七牛云SDK-->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.7.0, 7.7.99]</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
配置七牛云
spring:
application:
name: demo
# 上传文件大小默认1MB 超过1MB会报错
servlet:
multipart:
# 不限制大小 可以修改为其他指定大小 如 2000MB
max-file-size: -1
max-request-size: -1
server:
port: 8085
qiniu:
accessKey: # 公钥
secretKey: # 私钥
bucketName: #存储空间名称
path: 域名地址
编写业务功能代码
DemoApplication.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
七牛云上传配置类
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@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 com.qiniu.storage.Configuration());
}
}
工具类 QiniuUtils.java
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.FileInputStream;
@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.java
import java.util.UUID;
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 uuid + suffix;
}
}
统一结果响应类
import lombok.Data;
import org.springframework.http.HttpStatus;
import java.io.Serializable;
import java.util.HashMap;
@Data
public class Result<T> extends HashMap<String, Object> implements Serializable {
private int code;
private String message;
private T data;
public Result(String message) {
super.put("code", HttpStatus.OK.value());
super.put("message", message);
}
public Result(int code, String message) {
super.put("code", code);
super.put("message", message);
}
public Result(String message, T data) {
super.put("code", HttpStatus.OK.value());
super.put("message", message);
super.put("data", data);
}
public static Result buildSuccessMsg(String message) {
return new Result(message);
}
public static Result buildSuccessData(String message, Object data) {
return new Result(message, data);
}
public static Result buildFailMsg(int code, String message) {
return new Result(code, message);
}
}
service层
import com.qiniuyun.demo.entity.Result;
import org.springframework.web.multipart.MultipartFile;
public interface PictureService {
Result<String> upload(MultipartFile file);
}
service实现类
import com.qiniuyun.demo.entity.Result;
import com.qiniuyun.demo.service.PictureService;
import com.qiniuyun.demo.utils.QiniuUtils;
import com.qiniuyun.demo.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Objects;
@Service
public class PictureServiceImpl implements PictureService {
@Autowired
private QiniuUtils qiniuUtils;
@Override
public Result upload(MultipartFile file) {
if (file.isEmpty()) {
return Result.buildFailMsg(HttpStatus.ACCEPTED.value(), "上传文件为空,请重试...");
}
String fileName = StringUtils.getRandomImgName(Objects.requireNonNull(file.getOriginalFilename()));
try {
FileInputStream uploadFile = (FileInputStream) file.getInputStream();
String path = qiniuUtils.upload(uploadFile, fileName);
return Result.buildSuccessData("上传成功...", path);
} catch (IOException e) {
e.printStackTrace();
return Result.buildFailMsg(HttpStatus.INTERNAL_SERVER_ERROR.value(), "服务器内部错误...");
}
}
}
controller层
import com.qiniuyun.demo.entity.Result;
import com.qiniuyun.demo.service.PictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@CrossOrigin
public class PictureController {
@Autowired
private PictureService pictureService;
@PostMapping(value = "/upload")
public Result upload(@RequestParam("file") MultipartFile file) {
return pictureService.upload(file);
}
}
启动项目
postman测试
将返回来的图片地址复制到浏览器即可查看图片或者视频等文件
|