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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_28929589/article/details/79199462

通过客服端进行表单提交文件域,以服务器为媒介进行数据传输到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();
				}	
	}

熟悉的人就知道怎么做了

展开阅读全文

没有更多推荐了,返回首页