jar包导入
< dependency>
< groupId> com. amazonaws< / groupId>
< artifactId> aws- java- sdk- s3< / artifactId>
< version> 1.11 .600 < / version>
< scope> compile< / scope>
< / dependency>
yml引入配置
#amazon上传文件
amazon:
s3:
accessKey: AKIAU
secretKey: 0 MXTb
bucketName: wo
host: https: / / 存储桶名称. s3. us- east- 2. amazonaws. com
fileMaxSize: 50 #文件最大大小,单位M
imageAutoZip: true #图片是否自动压缩,true 是,默认false
imageQuality: 0.5 #图片质量,默认0.5
配置Config
import com. amazonaws. auth. BasicAWSCredentials ;
import com. amazonaws. services. s3. AmazonS3 ;
import com. amazonaws. services. s3. AmazonS3Client ;
import lombok. Data ;
import org. springframework. beans. factory. annotation. Value ;
import org. springframework. context. annotation. Bean ;
import org. springframework. context. annotation. Configuration ;
@Data
@Configuration
public class AmazonFileConfig {
@Value ( "${amazon.s3.accessKey}" )
private String accessKey;
@Value ( "${amazon.s3.secretKey}" )
private String secretKey;
@Value ( "${amazon.s3.bucketName}" )
private String bucketName;
@Value ( "${amazon.s3.host}" )
private String host;
@Value ( "${amazon.s3.fileMaxSize}" )
private int fileMaxSize;
@Value ( "${amazon.s3.imageAutoZip}" )
private boolean imageAutoZip = false ;
@Value ( "${amazon.s3.imageQuality}" )
private float imageQuality = 0.5F ;
@Bean
public AmazonS3 amazonS3 ( ) {
return new AmazonS3Client ( new BasicAWSCredentials ( accessKey, secretKey) ) ;
}
}
上传文件代码
@Autowired
private AmazonS3 s3;
@Value ( "${spring.profiles.active}" )
private String active;
@Autowired
private AmazonFileConfig fileConfig;
private static List < String > EXCLUSION_EXT_NAME = new ArrayList ( ) ;
static {
String exclusionExtName = "jar|jsp|jspx|asp|aspx|sh|pl|php|bat|war" ;
EXCLUSION_EXT_NAME = Splitter . on ( '|' ) . omitEmptyStrings ( ) . splitToList ( exclusionExtName) ;
}
@Override
public FileEntity uploadFile ( MultipartFile file, String filePath) throws Exception {
if ( file == null ) {
throw new InvokeException ( - 2002 , "文件不能为空!" ) ;
} else {
String fileName = file. getOriginalFilename ( ) ;
String extName = FilenameUtils . getExtension ( fileName) ;
if ( StringUtils . isBlank ( extName) ) {
return null ;
}
if ( EXCLUSION_EXT_NAME. contains ( extName. toLowerCase ( ) ) ) {
throw new InvokeException ( - 2006 , "禁止上传[" + extName + "]文件类型!" ) ;
} else {
InputStream is = file. getInputStream ( ) ;
long fileSize = ( long ) is. available ( ) ;
if ( fileSize > ( long ) fileConfig. getFileMaxSize ( ) * 1024 * 1024 ) {
throw new InvokeException ( - 2005 , "文件大小超出限制!" ) ;
} else {
if ( filePath == null || filePath == "" ) {
filePath = active + "/" + DateHelper . formatDate ( new Date ( ) , "yyyy/MM/dd/HH" ) + "/" + StringHelper . getUUID ( ) + "." + extName;
}
InputStream inputStream = getInputStream ( file) ;
filePath = this . uploadToS3 ( inputStream, filePath) ;
FileEntity fileEntity = new FileEntity ( ) ;
fileEntity. setFilePath ( filePath) ;
fileEntity. setFileSize ( fileSize) ;
fileEntity. setFileName ( fileName) ;
fileEntity. setExtName ( extName) ;
this . saveFile ( fileEntity) ;
return fileEntity;
}
}
}
}
public String uploadToS3 ( InputStream inputStream, String remoteFileName) {
try {
String bucketName = fileConfig. getBucketName ( ) ;
ObjectMetadata metadata = new ObjectMetadata ( ) ;
if ( remoteFileName. endsWith ( "jpg" ) || remoteFileName. endsWith ( "jpeg" ) || remoteFileName. endsWith ( "png" ) ) {
metadata. setContentType ( "image/jpeg;application/octet-stream" ) ;
}
s3. putObject ( new PutObjectRequest ( bucketName, remoteFileName, inputStream, metadata)
. withCannedAcl ( CannedAccessControlList. PublicRead ) ) ;
GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest ( bucketName, remoteFileName) ;
URL url = s3. generatePresignedUrl ( urlRequest) ;
log. info ( "upload file path :" + url. toString ( ) ) ;
String path = this . dealS3Url ( url. toString ( ) ) ;
return path;
} catch ( Exception ase) {
ase. printStackTrace ( ) ;
}
return null ;
}
private String dealS3Url ( String path) {
int index = path. indexOf ( "?" ) ;
if ( index == - 1 ) {
return path;
}
return path. substring ( 0 , index) ;
}
@Override
public void removeAwsFile ( String url) {
String key = url. replace ( fileConfig. getHost ( ) + "/" , "" ) ;
s3. deleteObject ( fileConfig. getBucketName ( ) , key) ;
}
private InputStream getInputStream ( MultipartFile file) throws IOException {
if ( fileConfig. isImageAutoZip ( ) ) {
try {
String extName = FilenameUtils . getExtension ( file. getOriginalFilename ( ) ) ;
if ( Pattern . matches ( "jpg|jpeg|png" , extName. toLowerCase ( ) ) ) {
ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ;
BufferedImage bufferedImage = Thumbnails . of ( new InputStream [ ] { file. getInputStream ( ) } ) . scale ( 1.0D ) . outputQuality ( fileConfig. getImageQuality ( ) ) . asBufferedImage ( ) ;
ImageIO . write ( bufferedImage, extName, os) ;
return new ByteArrayInputStream ( os. toByteArray ( ) ) ;
}
} catch ( IOException var4) {
}
}
return file. getInputStream ( ) ;
}
private void saveFile ( FileEntity fileEntity) {
MFile file = new MFile ( ) ;
file. setUrl ( fileEntity. getFilePath ( ) ) ;
file. setFileName ( fileEntity. getFileName ( ) ) ;
file. setExtName ( fileEntity. getExtName ( ) ) ;
file. setCreateTime ( new Date ( ) ) ;
fileMapper. insert ( file) ;
}