LZ看了半天文档全是英文 翻译还有语法错误,这对英文水平低下的我来说不能容忍,在网上也找了很久都没有实用的资料
所以自己琢磨了一下就弄个demo看看吧。。
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* Created by Administrator on 2018/7/5
*/
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.*;
import com.amazonaws.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
public class S3Util {
public static AWSCredentials awsCredentials;
public static String access_key = "你的key";
private static String secret_key = "你的密钥";
private static AmazonS3 conn;
private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");//设置日期格式
/**
* 创建连接,连接S3服务器
*/
public void creatConnect() {
if (awsCredentials == null) {
awsCredentials = new BasicAWSCredentials(access_key, secret_key);
ClientConfiguration clientConfig = new ClientConfiguration();
clientConfig.setProtocol(Protocol.HTTP);
conn = new AmazonS3Client(awsCredentials, clientConfig);
}
}
public AmazonS3 getConnect() {
return conn;
}
/**
* 获取该连接下所有的容器信息
* @return
*/
public List<Bucket> getBuckets() {
List<Bucket> buckets = conn.listBuckets();
return buckets;
}
public Bucket getBuketsByname(String bucketName) {
Bucket resultBucket = null;
if (bucketName.isEmpty()) {
return null;
}
List<Bucket> buckets = conn.listBuckets();
if(buckets == null){
return resultBucket;
}
for (Bucket bucket : buckets) {
if (bucketName.equals(bucket.getName())) {
resultBucket = bucket;
break;
}
}
return resultBucket;
}
/**
* 新建容器名称
* @param bucketName
* @return
*/
public Bucket creatBucket(String bucketName) {
if (bucketName.isEmpty()) {
return null;
}
Bucket bucket = conn.createBucket(bucketName);
return bucket;
}
/**
* 获取该容器下面的所有信息(文件目录集合和文件信息集合)
* @param bucketName
* @return
*/
public ObjectListing getBacketObjects(String bucketName) {
if (bucketName.isEmpty()) {
return null;
}
ObjectListing objects = conn.listObjects(bucketName);
return objects;
}
/**
* 获取某个文件(前缀路径)下的所有信息
* @param bucketName
* @param prefix
* @param isDelimiter
* @return
*/
public ObjectListing getBacketObjects(String bucketName, String prefix,Boolean isDelimiter ) {
if ( bucketName == null || bucketName.isEmpty()) {
return null;
}
ListObjectsRequest objectsRequest = new ListObjectsRequest().withBucketName(bucketName);
if (prefix != null && !prefix.isEmpty()) {
objectsRequest = objectsRequest.withPrefix(prefix);
}
if(isDelimiter){
objectsRequest = objectsRequest.withDelimiter("/");
}
ObjectListing objects = conn.listObjects(objectsRequest);
return objects;
}
/**
* 获取当前容器下面的目录集合
* @param objects
* @return
*/
/* public List<StorageObjectVo> getDirectList(ObjectListing objects) {
List<StorageObjectVo> diectList = new ArrayList<StorageObjectVo>();
String prefix = objects.getPrefix();
do {
List<String> commomprefix = objects.getCommonPrefixes();
for (String comp : commomprefix) {
StorageObjectVo dirStorageObjectVo = new StorageObjectVo();
String dirName = comp.substring(prefix == null?0:prefix.length(), comp.length()-1);
dirStorageObjectVo.setName(dirName);
dirStorageObjectVo.setType("文件夹");
diectList.add(dirStorageObjectVo);
}
objects = conn.listNextBatchOfObjects(objects);
} while (objects.isTruncated());
return diectList;
} */
/**
* 获取当前容器下面的文件集合
* @param objects
* @return
*/
/* public List<StorageObjectVo> getFileList(ObjectListing objects) {
List<StorageObjectVo> fileList = new ArrayList<StorageObjectVo>();
String prefix = objects.getPrefix();
do {
for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
System.out.println(objectSummary.getKey() + "\t" + objectSummary.getSize() + "\t" + StringUtils.fromDate(objectSummary.getLastModified()));
if(prefix!= null && objectSummary.getKey().equals(prefix.trim())){
continue;
}
StorageObjectVo fileStorageObjectVo = new StorageObjectVo();
String fileName = objectSummary.getKey().substring(prefix == null?0:prefix.length(), objectSummary.getKey().length());
// fileStorageObjectVo.setName(objectSummary.getKey());
fileStorageObjectVo.setName(fileName);
fileStorageObjectVo.setType("文件");
fileStorageObjectVo.setSize(bytes2kb(objectSummary.getSize()));
fileStorageObjectVo.setDate(df.format(objectSummary.getLastModified()));
fileList.add(fileStorageObjectVo);
}
objects = conn.listNextBatchOfObjects(objects);
} while (objects.isTruncated());
return fileList;
}
public List<StorageObjectVo> getObjectList(String bucketName, String prefix) {
if ( bucketName == null && bucketName.isEmpty()) {
return null;
}
ListObjectsRequest objectsRequest = new ListObjectsRequest().withBucketName(bucketName);
if (prefix!=null && !prefix.isEmpty()) {
objectsRequest = objectsRequest.withPrefix(prefix);
}
objectsRequest = objectsRequest.withDelimiter("/");
ObjectListing objects = conn.listObjects(objectsRequest);
List<StorageObjectVo> resultList = new ArrayList<StorageObjectVo>();
List<StorageObjectVo> dirList = getDirectList(objects);
if (dirList != null && dirList.size() > 0) {
resultList.addAll(dirList);
}
List<StorageObjectVo> fileList = getFileList(objects);
if (fileList != null && fileList.size() > 0) {
resultList.addAll(fileList);
}
return resultList;
} */
//创建文件目录
public Boolean creatpath(String bucketName,String StorageObjectVoPath, String folderName){
if(bucketName == null || folderName == null){
return false;
}
if(StorageObjectVoPath == null || StorageObjectVoPath.isEmpty()|| "null".equals(StorageObjectVoPath)){
StorageObjectVoPath ="";
}
String key = StorageObjectVoPath + folderName+"/";
ByteArrayInputStream local = new ByteArrayInputStream("".getBytes());
PutObjectResult result = conn.putObject(bucketName, key, local, new ObjectMetadata());
return true;
}
public Boolean deleteBucket(String bucketName) {
if (bucketName.isEmpty()) {
return false;
}
Bucket bucket = conn.createBucket(bucketName);
conn.deleteBucket(bucket.getName());
return true;
}
/**
*
* 上传 文件对象到容器
* @param bucketName
* @param StorageObjectVoPath
* @param fileName
* @param uploadFile
* @return
*/
public PutObjectResult creatObject(String bucketName,String StorageObjectVoPath, String fileName, File uploadFile) {
if(StorageObjectVoPath == null || StorageObjectVoPath.isEmpty()|| "null".equals(StorageObjectVoPath)){
StorageObjectVoPath ="";
}
if(uploadFile == null){
return null;
}
String fileAllPath = StorageObjectVoPath + fileName;
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(uploadFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
PutObjectResult result = conn.putObject(bucketName, fileAllPath, inputStream, new ObjectMetadata());
return result;
}
public void changeOBjectACL(String bucketName, String ObjectName, CannedAccessControlList aceess) {
conn.setObjectAcl(bucketName, ObjectName, aceess);
}
public ObjectMetadata download(String bucketName, String objectName, File destinationFile) {
if (bucketName.isEmpty() || objectName.isEmpty()) {
return null;
}
ObjectMetadata result = conn.getObject(new GetObjectRequest(bucketName, objectName), destinationFile);
return result;
}
public S3Object download(String bucketName, String objectName) {
if (bucketName.isEmpty() || objectName.isEmpty()) {
return null;
}
S3Object object = conn.getObject(bucketName, objectName);
return object;
}
public Boolean deleteObject(String bucketName, String objectName) {
if (bucketName.isEmpty() || objectName.isEmpty()) {
return false;
}
conn.deleteObject(bucketName, objectName);
return true;
}
/**生成文件url
*
* @param bucketName
* @param objectName
* @return
*/
public String getDownloadUrl(String bucketName, String objectName) {
if (bucketName.isEmpty() || objectName.isEmpty()) {
return null;
}
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName);
System.out.println(conn.generatePresignedUrl(request));
return conn.generatePresignedUrl(request).toString();
}
/**
* 移动对象信息到目标容器
* @param OrgbucketName
* @param orgKey
* @param destinationName
* @param destinationKey
* @return
*/
public Boolean moveObject(String OrgbucketName,String orgKey,String destinationName,String destinationKey){
CopyObjectResult result=conn.copyObject(OrgbucketName, orgKey, destinationName, destinationKey);
Boolean isDelete=deleteObject(OrgbucketName,orgKey);
if(result!=null){
return isDelete;
}
return false;
}
/**
* 移动目标文件夹信息到目标容器
* @param objects
* @param destinationBucket
* @return
*/
public Boolean moveForder(ObjectListing objects,String destinationBucket){
String bucketName = objects.getBucketName();
do {
for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
System.out.println(objectSummary.getKey() + "\t" + objectSummary.getSize() + "\t" + StringUtils.fromDate(objectSummary.getLastModified()));
CopyObjectResult result=conn.copyObject(bucketName, objectSummary.getKey(), destinationBucket, objectSummary.getKey());
Boolean isDelete=deleteObject(bucketName, objectSummary.getKey());
}
objects = conn.listNextBatchOfObjects(objects);
} while (objects.isTruncated());
return true;
}
/**
* 删除文件夹内容(必须先遍历删除文件夹内的内容)
* @param objects
* @return
*/
public Boolean deleteForder(ObjectListing objects){
String bucketName = objects.getBucketName();
do {
for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
System.out.println(objectSummary.getKey() + "\t" + objectSummary.getSize() + "\t" + StringUtils.fromDate(objectSummary.getLastModified()));
Boolean isDelete=deleteObject(bucketName, objectSummary.getKey());
}
objects = conn.listNextBatchOfObjects(objects);
} while (objects.isTruncated());
return true;
}
/**
* 将文件大小格式转为MB格式
* @param bytes
* @return
*/
public static String bytes2kb(long bytes) {
BigDecimal filesize = new BigDecimal(bytes);
BigDecimal megabyte = new BigDecimal(1024 * 1024);
float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP)
.floatValue();
if (returnValue > 1)
return (returnValue + "MB");
BigDecimal kilobyte = new BigDecimal(1024);
returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP)
.floatValue();
return (returnValue + "KB");
}
}
里面这些逻辑我就不详解了 应该都能看的懂 具体的demo我会传到文件里 有兴趣的自行下载测试 。。
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
* 图片上传
*/
@Api(description = "北美S3图片上传")
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
public class PictureUploadController {
//服务器盘,如需新建桶,需要先将下面创建桶开启
private static final String BucektName = "rentao";
//路径前缀
//private final static String url="https://s3.amazonaws.com/";//此地址服务器在美国
// private final static String url="https://s3-ap-southeast-1.amazonaws.com/";//此地址服务器在新加坡
private final static String url = "https://s3-us-west-1.amazonaws.com/";//此地址服务器在加利福利亚北部
@ApiOperation(value = "图片上传", notes = "图片上传")
@RequestMapping(value = "/img/upload.do", method = RequestMethod.POST)
public ResponseEntity<JsonResultEntity> insert(@RequestParam(value = "picture", required = true) MultipartFile uploadFile,
@RequestParam(value = "width", defaultValue = "0", required = false) int width,
@RequestParam(value = "height", defaultValue = "0", required = false) int height) {
// 图片名称和后缀判断
String fileName = uploadFile.getOriginalFilename();
//判断是否为图片格式 采用正则表达式
String fileType = fileName.substring(fileName.lastIndexOf("."));
if (!fileType.matches("^.*(jpg|png|gif|jpeg)$")) {
//表示不是图片类型
return ResponseEntity.ok(JsonResultUtils.error(MessageEnum.PIC_NOT_NORM.getCode(),
MessageEnum.PIC_NOT_NORM.getMessage()));
// Result.errorReponse("上传文件不是正确的图片格式,上传出错!");
}
//判断是否为恶意程序
try {
BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream());
//获取图片的高度和宽度
int imageWidth = bufferedImage.getWidth();
int imageHeight = bufferedImage.getHeight();
if (imageWidth == 0 || imageHeight == 0) {
return ResponseEntity.ok(JsonResultUtils.error(MessageEnum.PIC_NOT_NORM.getCode(),
MessageEnum.PIC_NOT_NORM.getMessage()));
// Result.errorReponse("上传文件非图片类型,上传出错!");
}
} catch (IOException e1) {
e1.printStackTrace();
}
//新建两个临时文件,将内存中的图片放入临时文件中,方便图片转换
File f = null;
File toPic = null;
try {
//将图片转为File类型
f = File.createTempFile("tmp", fileType);
uploadFile.transferTo(f);
//设置图片压缩比例。
toPic = File.createTempFile("topic", fileType);
Thumbnails.of(f).scale(1f).outputQuality(0.25f).toFile(toPic);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.ok(JsonResultUtils.error(MessageEnum.PIC_UPLOAD_ERROR.getCode(),
MessageEnum.PIC_UPLOAD_ERROR.getMessage()));
// Result.errorReponse("上传图片失败,请重新提交!");
}
String url = uploadS3File(toPic, width, height);
//删除两个临时文件
f.deleteOnExit();
toPic.deleteOnExit();
if (!url.startsWith("https")) {
return ResponseEntity.ok(JsonResultUtils.error(MessageEnum.PIC_UPLOAD_ERROR.getCode(),
MessageEnum.PIC_UPLOAD_ERROR.getMessage()));
}
return ResponseEntity.ok(
JsonResultUtils.success(url, MessageEnum.COMMON_STATUS_OK.getCode(), MessageEnum.COMMON_STATUS_OK.getMessage()));
// Result.normalResponse(url);
}
public String uploadS3File(File file, int width, int height) {
//连接远程图片服务器
S3Util s3 = new S3Util();
s3.creatConnect();
String fileType = file.getName().substring(file.getName().lastIndexOf("."));
//准备路径
Random random = new Random();
//0-999的随机数,用于区分上传文件的文件夹,避免图片上传冲突
int randomNum = random.nextInt(999);
String StorageObjectVoPath = new SimpleDateFormat("yyyy/MM/dd/HH").format(new Date()) + "/" + randomNum + "/";
//创建网上bucket的名字,如需新建桶,需要先将此处开启
/*if(s3.getBuketsByname(BucektName)==null) {
s3.creatBucket(BucektName);
}*/
BufferedImage image = null;
try {
image = ImageIO.read(file);
} catch (IOException e1) {
e1.printStackTrace();
}
int imageWidth = image.getWidth();
int imageHeitht = image.getHeight();
//如果上传图片没有长宽的值,则默认按照原图尺寸上传,执行下面if代码结束
if (width == 0 && height == 0) {
String fileName = System.currentTimeMillis() + "_" + imageWidth + "X" + imageHeitht + fileType;
s3.creatObject(BucektName, StorageObjectVoPath, fileName, file);
//代表虚拟的全路径
String url = PictureUploadController.url + BucektName + "/" + StorageObjectVoPath + fileName;
return url;
}
//等比例缩放,等比例只需要传一个值即可
if (width != height) {
File toPic = null;
try {
toPic = File.createTempFile("topic", fileType);
//按比例缩放
if (width == 0) {
Thumbnails.of(file).scale((double) height / imageHeitht).toFile(toPic);
} else {
Thumbnails.of(file).scale((double) width / imageWidth).toFile(toPic);
}
toPic.deleteOnExit();
image = ImageIO.read(toPic);
} catch (IOException e) {
e.printStackTrace();
}
//设置文件名
width = image.getWidth();
height = image.getHeight();
String fileName = System.currentTimeMillis() + "_" + width + "X" + height + fileType;
s3.creatObject(BucektName, StorageObjectVoPath, fileName, toPic);
//代表虚拟的全路径
String url = PictureUploadController.url + BucektName + "/" + StorageObjectVoPath + fileName;
return url;
}
//如果长宽均有值且相等,则执行下面的代码上传图片压缩的值
if (imageWidth < imageHeitht) {
imageHeitht = imageWidth;
} else {
imageWidth = imageHeitht;
}
File toPic = null;
try {
toPic = File.createTempFile("topic", fileType);
//截取图片成正方形
Thumbnails.of(file).sourceRegion(Positions.CENTER, imageWidth, imageHeitht).size(imageWidth, imageHeitht).toFile(toPic);
Thumbnails.of(toPic).scale((double) width / imageWidth).toFile(toPic);
} catch (IOException e) {
e.printStackTrace();
}
//设置文件名
String fileName = System.currentTimeMillis() + "_" + width + "X" + height + fileType;
s3.creatObject(BucektName, StorageObjectVoPath, fileName, toPic);
toPic.deleteOnExit();
//代表虚拟的全路径
String url = PictureUploadController.url + BucektName + "/" + StorageObjectVoPath + fileName;
return url;
}
}
具体的就去demo里面吧 在文件里面