Springboot 통합 아 리 클 라 우 드 OSS 업로드 파일 시스템 튜 토리 얼
7007 단어 Springboot아 리 운oss문건업로드
두 번 째 단계:공식 문서 에 따라 업로드 코드 를 작성 합 니 다.
1.새 maven 항목
의존 도 추가:
<!-- oss -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</dependency>
<!-- -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
2.application.properties 설정
#
server.port=8002
#
spring.application.name=service-oss
# :dev、test、prod
spring.profiles.active=dev
# OSS
# ,
aliyun.oss.file.endpoint=your endpoint
aliyun.oss.file.keyid=your accessKeyId
aliyun.oss.file.keysecret=your accessKeySecret
#bucket , java
aliyun.oss.file.bucketname=guli-file
3.시작 클래스 만 들 기OssApplication.java 만 들 기
package com.sun.oss;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan({"com.sun"})
public class OssApplication {
public static void main(String[] args) {
SpringApplication.run(OssApplication.class, args);
}
}
시작 오류:다 중 모듈 을 응용 할 때 이 모듈 은 데이터 베 이 스 를 사용 하지 않 았 고 프로필 에 데이터베이스 설정 정보 가 없 으 면 오류 가 발생 할 수 있 습 니 다.
첫 번 째 방법:
설정 클래스 에 데이터베이스 설정 정 보 를 추가 합 니 다:
# mysql
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/musicdb?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
두 번 째 방법:주 해 를 추가 하고@SpringBootApplication 주해 에 exclude 를 추가 하여 DataSourceAutoConfiguration 자동 로드 를 해제 합 니 다.
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
4.도구 클래스 만 들 기:프로필 키 정보 읽 기
ConstantPropertiesUtils.java
// ,spring ,spring ,
@Component
public class ConstantPropertiesUtils implements InitializingBean {
//
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.keyid}")
private String keyId;
@Value("${aliyun.oss.file.keysecret}")
private String keySecret;
@Value("${aliyun.oss.file.bucketname}")
private String bucketName;
//
public static String END_POIND;
public static String ACCESS_KEY_ID;
public static String ACCESS_KEY_SECRET;
public static String BUCKET_NAME;
@Override
public void afterPropertiesSet() throws Exception {
END_POIND = endpoint;
ACCESS_KEY_ID = keyId;
ACCESS_KEY_SECRET = keySecret;
BUCKET_NAME = bucketName;
}
}
5.controller 클래스 작성
@Api(description = " oss")
@RestController
@RequestMapping("/eduoss/fileoss")
@CrossOrigin//
public class OssController {
@Autowired
private OssService ossService;
//
@ApiOperation(" ")
@PostMapping
public R uploadOssFile(MultipartFile file) {
// MultipartFile
// oss
String url = ossService.uploadFileAvatar(file);
return R.ok().data("url",url);
}
}
6.service 클래스 작성
@Service
public class OssServiceImpl implements OssService {
//
@Override
public String uploadFileAvatar(MultipartFile file) {
//
String endPoind = ConstantPropertiesUtils.END_POIND;
String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
try {
// Oss
OSS ossClient = new OSSClientBuilder().build(endPoind, accessKeyId, accessKeySecret);
//
InputStream inputStream = file.getInputStream();
//
String filename = file.getOriginalFilename();
//1. , UUid
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// fileName
filename=uuid+filename;
//2.
// , org.joda.time
String datePath = new DateTime().toString("yyyy/MM/dd");
//
filename=datePath+"/"+filename;
// oss
// Bucket
// oss
//
ossClient.putObject(bucketName,filename,inputStream);
// OssClient
ossClient.shutdown();
//
// oss
//https://edu-975.oss-cn-beijing.aliyuncs.com/07aef13af7ea82703f3eb320c3f577ec.jpg
String url="https://"+bucketName+"."+endPoind+"/"+filename;
return url;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}
업로드 파일 크기 해결:
#
spring.servlet.multipart.max-request-size=10MB
#
spring.servlet.multipart.max-file-size=3MB
swagger 테스트 실행:성공!!
Springboot 통합 아 리 클 라 우 드 OSS 업로드 파일 시스템 튜 토리 얼 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 Springboot 통합 아 리 클 라 우 드 oss 파일 업로드 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 많은 지원 바 랍 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[MeU] Hashtag 기능 개발➡️ 기존 Tag 테이블에 존재하지 않는 해시태그라면 Tag , tagPostMapping 테이블에 모두 추가 ➡️ 기존에 존재하는 해시태그라면, tagPostMapping 테이블에만 추가 이후에 개발할 태그 기반 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.