下面是一个 DTO 类,它接收直接从客户端传入的 base64Image 数据,并将其解析为可以在 uploadToAwsS3 方法中轻松传递的不同组件:
public class Base64ImageDto {
private byte[] imageBytes;
private String fileName;
private String fileType;
private boolean hasErrors;
private List<String> errorMessages;
private static final List<String> VALID_FILE_TYPES = new ArrayList<String>(3);
static {
VALID_FILE_TYPES.add("jpg");
VALID_FILE_TYPES.add("jpeg");
VALID_FILE_TYPES.add("png");
}
public Base64ImageDto(String b64ImageData, String fileName) {
this.fileName = fileName;
this.errorMessages = new ArrayList<String>(2);
String[] base64Components = b64ImageData.split(",");
if (base64Components.length != 2) {
this.hasErrors = true;
this.errorMessages.add("Invalid base64 data: " + b64ImageData);
}
if (!this.hasErrors) {
String base64Data = base64Components[0];
this.fileType = base64Data.substring(base64Data.indexOf('/') + 1, base64Data.indexOf(';'));
if (!VALID_FILE_TYPES.contains(fileType)) {
this.hasErrors = true;
this.errorMessages.add("Invalid file type: " + fileType);
}
if (!this.hasErrors) {
String base64Image = base64Components[1];
this.imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
}
}
}
public byte[] getImageBytes() {
return imageBytes;
}
public void setImageBytes(byte[] imageBytes) {
this.imageBytes = imageBytes;
}
public boolean isHasErrors() {
return hasErrors;
}
public void setHasErrors(boolean hasErrors) {
this.hasErrors = hasErrors;
}
public List<String> getErrorMessages() {
return errorMessages;
}
public void setErrorMessages(List<String> errorMessages) {
this.errorMessages = errorMessages;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
您可以向 AwsS3Service 中添加以下方法,该方法会将对象放在那里 (注意:您可能没有使用传输管理器来管理看跌期权,因此您需要相应地更改该代码):
public void uploadBase64Image(Base64ImageDto base64ImageDto, String pathToFile) {
InputStream stream = new ByteArrayInputStream(base64ImageDto.getImageBytes());
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(base64ImageDto.getImageBytes().length);
metadata.setContentType("image/"+base64ImageDto.getFileType());
String bucketName = awsS3Configuration.getBucketName();
String key = pathToFile + base64ImageDto.getFileName();
try {
LOGGER.info("Uploading file " + base64ImageDto.getFileName() + " to AWS S3");
PutObjectRequest objectRequest = new PutObjectRequest(bucketName, key, stream, metadata);
objectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
Upload s3FileUpload = s3TransferManager.upload(objectRequest);
s3FileUpload.waitForCompletion();
} catch (Exception e) {
e.printStackTrace();
LOGGER.info("Error uploading file " + base64ImageDto.getFileName() + " to AWS S3");
}
}