Created
May 19, 2017 17:16
-
-
Save DaddyMoe/6f4b7bf8c058b78e0b67d214bd2fd334 to your computer and use it in GitHub Desktop.
Upload image to S3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.io.InputStream; | |
import org.springframework.web.multipart.MultipartFile; | |
import com.amazonaws.AmazonServiceException; | |
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.CannedAccessControlList; | |
import com.amazonaws.services.s3.model.ObjectMetadata; | |
import com.amazonaws.services.s3.model.PutObjectRequest; | |
public class ImageS3Util { | |
private static final String ACCESS_KEY = "xxx"; | |
private static final String SECRET_KEY = "xxx"; | |
private static final String END_POINT_URL = "xxx";// e.g http://s3.amazonaws.com | |
private static final String BUCKET = "xxx"; | |
private static final String IMAGE_LOCATION = "xxx"; | |
private static final String S3_CACHE = "xxx"; // e.g 60 | |
private static AmazonS3 s3; | |
public static void uploadImageToAWSS3(MultipartFile multipartFile) throws IllegalStateException, | |
IOException { String fileName = null; | |
try { | |
AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY); | |
java.security.Security.setProperty("networkaddress.cache.ttl", S3_CACHE); | |
s3 = new AmazonS3Client(credentials); s3.setEndpoint(END_POINT_URL); | |
InputStream stream = multipartFile.getInputStream(); | |
fileName = System.currentTimeMillis() + "_" + fileName; | |
ObjectMetadata objectMetadata = new ObjectMetadata(); | |
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET, IMAGE_LOCATION + "/" + fileName, stream,objectMetadata); | |
//skip if do not want to access the image directly from S3 | |
putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead); | |
//skip if do not want to access the image directly from S3 | |
s3.putObject(putObjectRequest); | |
} catch (AmazonServiceException e) { | |
e.printStackTrace() | |
} | |
} | |
} | |
@RequestMapping(value = "/uploadImage", method = RequestMethod.POST) | |
@ResponseBody | |
public String uploadImage(@RequestParam("file") MultipartFile file, | |
HttpServletRequest request){ | |
if (!file.isEmpty()) { | |
filePath = ImageS3Util.uploadImageToAWSS3(file); | |
} | |
return "view page"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment