首先maven 构建 pom添加
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
application.yml 配置一些oss需要的参数
编写工具类OssUtils
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Component
public class OssUtils {
@Value("${oss.accessKeyId}")
public String accessKeyId;
@Value("${oss.accessKeySecret}")
public String accessKeySecret;
@Value("${oss.endpoint}")
public String endpoint;
@Value("${oss.bucketName}")
public String bucketName;
public static OSSClient client;
public OSSClient initClient(){
if(null==client){
ClientConfiguration conf = new ClientConfiguration();
conf.setConnectionTimeout(5000);
conf.setMaxErrorRetry(10);
client = new OSSClient("http://" + endpoint, accessKeyId, accessKeySecret,conf);
}
return client;
}
/**
* 上传文件
*
* @param fileKey
* @param content
* @throws FileNotFoundException
*/
public boolean putObjectForInputStream(String fileKey, InputStream content) {
if (null == fileKey || "" == fileKey.trim())
return false;
try {
initClient();
ObjectMetadata meta = new ObjectMetadata();
client.putObject(bucketName, fileKey, content, meta);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 上传图片
* @param imageName
* @param content
* @param if400
* @throws FileNotFoundException
*/
public String putObjectForImage(String imageName, InputStream content, boolean if400) {
if (null == imageName || "" == imageName.trim())
return null;
try {
String file = "images/" + imageName.substring(0, imageName.indexOf(".")) + "/" + imageName;
putObjectForInputStream(file,content);
return "http://"+bucketName+"."+endpoint+"/"+file;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String getObject(String key) {
try {
OSSObject object = client.getObject(bucketName, key);
InputStream objectContent = object.getObjectContent();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i = -1;
while ((i = objectContent.read()) != -1) {
baos.write(i);
}
objectContent.close();
return baos.toString("UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
接口实现方法这里写一个demo
@Resource
OssUtils imgUpload;
/**
* 上传人脸图片
*/
@PostMapping("uploadFaceData")
@ResponseBody
public ResultBody uploadFaceData(MultipartFile file) {
// 1.获取上传文件输入流
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
} catch (Exception e) {
return ResultBody.error(ErrorEnum.ADDHOTEL_PARAMS_ERROR);
}
String url= imgUpload.putObjectForImage("test.jpg",inputStream,false);
return ResultBody.success(url);
}
成功可以保存URL用于调取图片资源 打印控制台调试一下