hope to adopt: < br / > steps:
1. The front end uploads the file, and the name of the file to be uploaded is transmitted to the background
2. The background generates the pre-upload URL through the file name and returns the front-end
3. The front-end requests the URL and uploads the file to S3
Back-end code :
/**
* AWS预签名上传
* @return
*/
@GetMapping("/upload")
public Object generatePreSignedUrl(String fileName){
Map<String, Object> map = new HashMap<>();
try {
AWSCredentials awsCredentials = new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY);
AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(new ProfileCredentialsProvider())
.withRegion(Regions.CN_NORTH_1)
.withCredentials(awsCredentialsProvider)
.build();
java.util.Date expiration = new java.util.Date();
long expTimeMillis = expiration.getTime();
expTimeMillis += 1000 * 60 * 30;
expiration.setTime(expTimeMillis);
String name = fileName.substring(0,fileName.lastIndexOf("."));
String fileType = fileName.substring(fileName.lastIndexOf("."));
String prefixFileName = name+ "_"+String.valueOf(System.currentTimeMillis()).substring(6)+""+fileType;
Review review = new Review();
review.setName(name);
GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKET_NAME, prefixFileName)
.withMethod(HttpMethod.PUT)
.withExpiration(expiration);
URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
if(url == null){
return map;
}
// 文件访问地址
StringBuilder urlImage = new StringBuilder();
urlImage.append(url.getProtocol()).append("://").append(url.getHost()).
append(URLDecoder.decode(url.getPath(), "UTF-8"));
// 预签名put地址
StringBuilder preUrl = new StringBuilder();
preUrl.append(url.getProtocol()).append("://").append(url.getHost()).
append(URLDecoder.decode(url.getFile(), "UTF-8"));
map.put("preUrl",preUrl);
map.put("urlImage",urlImage);
return map;
} catch (Exception e) {
e.printStackTrace();
return map;
}
}
Front-end code :
import axios from 'axios'
axios.put(preUrl, fileList[0], {
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress: progressEvent => {
let complete = (progressEvent.loaded / progressEvent.total * 100.).toFixed(2)
}
})
.then((res: any) => {
if (res.status == 200) {
console.log(res)
}
}).catch(
err => {
console.log(err)
})
Of course,
can also be directly uploaded to AWS in the background. The back-end code is
. private void uploadContent(String imageUrl){
// Set the pre-signed URL to expire after one hour.
java.util.Date expiration = new java.util.Date();
long expTimeMillis = expiration.getTime();
expTimeMillis += 1000 * 60 * 5;
expiration.setTime(expTimeMillis);
// Generate the pre-signed URL.
String fileType = imageUrl.substring(imageUrl.lastIndexOf("."));
// 上传s3不保存后缀,
String prefixFileName = UUIDUtils.getUUID()+""+fileType;
GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKET_NAME, prefixFileName)
.withMethod( com.amazonaws.HttpMethod.PUT)
.withExpiration(expiration);
URL url = amazonS3.generatePresignedUrl(generatePresignedUrlRequest);
log.info("Generate the pre-signed URL: "+url);
// Create the connection and use it to upload the new object using the pre-signed URL.
HttpsURLConnection connection = null;
OutputStream out = null;
InputStream inputStream = null;
try {
// 需要上传的网络图片转为流
URL url1 = new URL(imageUrl);
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url1.openConnection();
inputStream = httpsURLConnection.getInputStream();
// 通过预签名url上传文件
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("PUT");
out = connection.getOutputStream();
byte[] arr = new byte[1024]; //该数组用来存入从输入文件中读取到的数据
int len; //变量len用来存储每次读取数据后的返回值
//while循环:每次从输入文件读取数据后,都写入到输出文件中
while( ( len=inputStream.read(arr) ) != -1 ) {
out.write( arr, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
can borrow this article: < br / > < a href = "https://blog.csdn.net/qq_43037478/article/details/118998706" target = "_blank" > < span > AWS S3 Implement pre-signed upload _ Love programming ape classmate's blog -CSDN blog s3 pre-signed