springBoot通过表单的提交进行AmazonS3 进行文件的上传下载删除(不存储在本地)。

16 篇文章 0 订阅
1 篇文章 0 订阅

通过客服端进行表单提交文件域,以服务器为媒介进行数据传输到AmazonS3服务器上。

首先在配置文件配置密钥,问公司拿

aws.accessKey=AKIAI2AH3BG
aws.secretKey=W0pu2gwVnAWAnVAQyP/up01B4v9thfhJ
aws.eweBucket=we-tt
然后创建一个类使用注解交给spring管理

package com.ewe.core.utils;



import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.ewe.user.controller.ShareFileController;
@Component
@SuppressWarnings("deprecation")
public final class AmazonS3Utils {
	private static final Logger logger = LoggerFactory.getLogger(ShareFileController.class);
	
	//申明变量
	@Value("${aws.accessKey}")
    private  String accessKeyID;
    @Value("${aws.secretKey}")
    private  String secretKey;
	@Value("${aws.eweBucket}")
    private  String bucketName;
    private  AWSCredentials credentials ;
	private   AmazonS3 s3Client;
	
    private  void getInit() {
		// TODO Auto-generated constructor stub
    	//初始化
    	if(s3Client==null){
    		 //创建Amazon S3对象
    		credentials = new BasicAWSCredentials(accessKeyID, secretKey);
    		s3Client = new AmazonS3Client(credentials);
    		 //设置区域 
    	    s3Client.setRegion(Region.getRegion(Regions.AP_SOUTHEAST_2));
    	}
	}
    /**
    * 查看所有可用的bucket
    * @param s3Client
     */
    public  void getAllBucket(AmazonS3 s3Client){
        List<Bucket> buckets = s3Client.listBuckets();
        for (Bucket bucket : buckets) {
            System.out.println("Bucket: " + bucket.getName());
        }
    }

    /**
     * 查看bucket下所有的object
     * @param bucketName 存储桶
     */
    public  void getAllBucketObject(AmazonS3 s3Client){
    	getInit();
        ObjectListing objects = s3Client.listObjects(bucketName);
        do {
            for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
                System.out.println("Object: " + objectSummary.getKey());
            }
            objects = s3Client.listNextBatchOfObjects(objects);
        } while (objects.isTruncated());
    }

    /**
     * amazonS3文件上传
     * @param s3Client 
     * @param bucketName 保存到某个存储桶
     * @param key 保存文件的key (以key-value形式保存)其实就是一个url路劲
     * @param file 上传文件
     */
    public  void amazonS3Upload(String key,byte[] data){
      	getInit();
      	ObjectMetadata metadata = new ObjectMetadata();
		metadata.setContentLength(data.length);
		PutObjectResult result = s3Client.putObject(bucketName, key, new ByteArrayInputStream(data), metadata);
		if (StringUtils.isNotBlank(result.getETag())) {
			logger.info("Send Data to Amazon S3 - Success, ETag is " + result.getETag());
		}
		logger.info("Send Data to Amazon S3 - End");
    }
    /**
     * amazonS3文件下载
     * @param s3Client
     * @param bucketName 下载某个存储桶的数据
     * @param key 下载文件的key
     * @param targetFilePath 下载文件保存地址
     */
    public  void amazonS3Downloading(String filePath,String fileName,HttpServletResponse response){
      	getInit();
    	S3Object object = s3Client.getObject(new GetObjectRequest(bucketName,filePath));
        if(object!=null){
            System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
            InputStream input = null;
           // FileOutputStream fileOutputStream = null;
            OutputStream out =null;
            byte[] data = null;
            try {
                //获取文件流
            	//信息头,相当于新建的名字
				response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                input=object.getObjectContent();
                data = new byte[input.available()];
                int len = 0;
            	out = response.getOutputStream();
                //fileOutputStream = new FileOutputStream(targetFilePath);
                while ((len = input.read(data)) != -1) {
                    out.write(data, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
            	//关闭输入输出流
                if(out!=null){
                    try {
                    	out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(input!=null){
                    try {
                        input.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 文件删除
     * @param s3Client
     * @param bucketName 删除文件所在存储桶
     * @param key 删除文件key
     */
    public  void amazonS3DeleteObject(String key){
    	getInit();
        s3Client.deleteObject(bucketName, key);
    }

    /**
     * 删除存储桶
     * @param s3Client
     * @param bucketName 需要删除的存储桶
     */
    public  void amazonS3DeleteBucket(AmazonS3 s3Client,String bucketName){
        s3Client.deleteBucket(bucketName);
    }

    //在文件比较大的时候,有必要用多线程上传。(未测试)
/*    TransferManager tm = new TransferManager(s3Client);  
    TransferManagerConfiguration conf = tm.getConfiguration();  

    int threshold = 4 * 1024 * 1024;  
    conf.setMultipartUploadThreshold(threshold);  
    tm.setConfiguration(conf);  

    Upload upload = tm.upload(bucketName, s3Path, new File(localPath));  
    TransferProgress p = upload.getProgress();  

    while (upload.isDone() == false)  
    {             
        int percent =  (int)(p.getPercentTransfered());
        Thread.sleep(500);  
    }   

    // 默认添加public权限  
    s3Client.setObjectAcl(bucketName, s3Path, CannedAccessControlList.PublicRead);
    */
  
 }
接下来在controller中通过请求获取表单域进行文件的提交

	@Autowired
	private AmazonS3Utils S3Util;
//省滤.............
controller中
@RequestMapping(value="/upload", method=RequestMethod.POST)
	public Object addFile(MultipartFile file,String category,HttpServletRequest request,HttpServletResponse response){
		LOGGER.info("-----------Start uploading files----------------");
			String fileName=file.getOriginalFilename();
			newInfo.setFileName(fileName);
			newInfo.setFilePath("HR/"+category);
			newInfo.setUuidName(FileUtil.generateFileName(newInfo.getFileName()));
			try {
				//文件的路劲
				String key=getKey(newInfo);
				//newInfo =FileUtil.uploadFile(file.getBytes(), newFileString,          file.getOriginalFilename());
				S3Util.amazonS3Upload(key, file.getBytes());
				LOGGER.info("Upload file success");
				try {
					newInfo=shareFileService.addFile(newInfo);
					LOGGER.info("Increased documentation success.");
					return newInfo.getId();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					LOGGER.info("Error in adding file records."+e);
					response.setStatus(500);
					userDto.setCode(500);
					userDto.setMessage(e.getCause()+"");
					e.printStackTrace();
				}	
	}

熟悉的人就知道怎么做了

在Spring Boot应用程序中,您可以使用`@RequestMapping`注解来创建一个处理文件下载请求的Controller。您可以在Controller中使用`S3TransferManager`下载文件并将其写入`ServletOutputStream`。下面是一个示例代码片段,演示如何将从Amazon S3下载的文件写入`ServletOutputStream`: ```java import com.amazonaws.services.s3.transfer.Download; import com.amazonaws.services.s3.transfer.TransferManager; import com.amazonaws.services.s3.transfer.TransferManagerBuilder; import com.amazonaws.services.s3.transfer.model.DownloadResult; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; @Controller public class FileDownloadController { @Value("${aws.s3.bucketName}") private String bucketName; @Value("${aws.s3.region}") private String region; @Value("${aws.s3.accessKeyId}") private String accessKeyId; @Value("${aws.s3.secretAccessKey}") private String secretAccessKey; @GetMapping("/download/{key}") public ResponseEntity<Resource> downloadFile(@PathVariable String key, HttpServletResponse response) throws IOException { TransferManager transferManager = TransferManagerBuilder.standard() .withS3Client(AmazonS3ClientBuilder.standard() .withRegion(region) .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKeyId, secretAccessKey))) .build()) .build(); File file = new File(key); Download download = transferManager.download(bucketName, key, file); InputStream inputStream = new FileInputStream(file); InputStreamResource resource = new InputStreamResource(inputStream); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + URLEncoder.encode(key, "UTF-8") + "\""); headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE); headers.add(HttpHeaders.CONTENT_LENGTH, file.length() + ""); headers.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate"); headers.add(HttpHeaders.PRAGMA, "no-cache"); headers.add(HttpHeaders.EXPIRES, "0"); return ResponseEntity.ok() .headers(headers) .body(resource); } } ``` 在上面的代码中,`@GetMapping("/download/{key}")`用于创建一个处理文件下载请求的Controller方法。`TransferManager`用于下载文件,其中`bucketName`是存储桶名称,`region`是存储桶所在的区域,`accessKeyId`和`secretAccessKey`是AWS的访问密钥。 在下载完成后,将文件内容写入`HttpServletResponse`中,通过设置`Content-Disposition`响应头,指定浏览器以附件形式下载文件。最后,将文件内容写入`InputStreamResource`并返回`ResponseEntity`对象。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值