0
Follow
2
View

s3 Generates a pre-signed URL. Uploading a file to an AWS report in a non-empty region must be provided in the credential

dege999 注册会员
2022-12-26 15:53
< div class =" md_content_show "data - v - d6147ea0 =" ">

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

About the Author

Question Info

Publish Time
2022-12-26 15:53
Update Time
2022-12-26 15:53

Related Question

UnsatisfiableError: The following specifications were found to be incompatible with each other:

linux为什么必须连网后才能收到组播数据

在Windows 10上从Visual Studio 2019构建Cuda静态库时出错

Linux中clion配置opencv

如何让PowerPoint VBA覆盖TXT文件中的特定行?

如何访问Spring控制器中的配置bean

PowerShell使用DisplayNames查找UserPrincipalName

在Terraform函数路径参数中使用S3对象

Javascript:函数等价于“for(let p in this)”

Intent可以传递的六类信息是什么