aws s3 通过java下载文件

springboot 项目使用

application-test.yml

  s3:
    endpoint: oos-cn.ctyunapi.cn
    accessKey: ??
    secretKey: ??
    bucketName: ??
    staticDomain: #http://bucket.oos-website-cn.oos-cn.ctyunapi.cn

S3Configuration.java

package org.jeecg.config.s3;

import org.jeecg.modules.system.util.S3Util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class S3Configuration {

    @Value("${jeecg.s3.endpoint}")
    private String endpoint;
    @Value("${jeecg.s3.accessKey}")
    private String accessKeyId;
    @Value("${jeecg.s3.secretKey}")
    private String accessKeySecret;
    @Value("${jeecg.s3.bucketName}")
    private String bucketName;
    @Value("${jeecg.s3.staticDomain}")
    private String staticDomain;


    @Bean
    public void initS3Configuration() {
    	S3Util.setEndPoint(endpoint);
    	S3Util.setAccessKeyId(accessKeyId);
    	S3Util.setAccessKeySecret(accessKeySecret);
    	S3Util.setBucketName(bucketName);
    	S3Util.setStaticDomain(staticDomain);
    }
}

S3Util.java

package org.jeecg.modules.system.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;

import org.apache.tomcat.util.http.fileupload.FileItemStream;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.web.multipart.MultipartFile;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CannedAccessControlList;
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.S3ObjectInputStream;


public class S3Util {

	private static String endPoint;
	private static String accessKeyId;
	private static String accessKeySecret;
	private static String bucketName;
	private static String staticDomain;

	public static void setEndPoint(String endPoint) {
		S3Util.endPoint = endPoint;
	}

	public static void setAccessKeyId(String accessKeyId) {
		S3Util.accessKeyId = accessKeyId;
	}

	public static void setAccessKeySecret(String accessKeySecret) {
		S3Util.accessKeySecret = accessKeySecret;
	}

	public static void setBucketName(String bucketName) {
		S3Util.bucketName = bucketName;
	}

	public static void setStaticDomain(String staticDomain) {
		S3Util.staticDomain = staticDomain;
	}

	/**
	 * oss 工具客户端
	 */
	private static AmazonS3 s3Client = null;
	private static String FILE_URL;

	/**
	 * AmazonS3 文件上传成功,返回文件完整访问路径 文件上传失败,返回 null
	 *
	 * @param file    待上传文件
	 * @param fileDir 文件保存目录
	 * @return oss 中的相对文件路径
	 */
	public static String upload(MultipartFile file, String fileDir) {
		initS3(endPoint, accessKeyId, accessKeySecret);
		StringBuilder fileUrl = new StringBuilder();
		try {
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
			String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
			if (!fileDir.endsWith("/")) {
				fileDir = fileDir.concat("/");
			}
			fileUrl = fileUrl.append(fileDir + fileName);

//			if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
//				FILE_URL = staticDomain + "/" + fileUrl;
//			} else {
//				FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
//			}
			FILE_URL = fileUrl.toString();
			ByteArrayInputStream input = new ByteArrayInputStream(file.getBytes());
			ObjectMetadata meta = new ObjectMetadata();
			meta.setContentLength(file.getSize());
			PutObjectResult result = s3Client.putObject(new PutObjectRequest(bucketName, fileUrl.toString(), input, meta));
			// 设置权限(公开读)
//			s3Client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
			if (result != null) {
				System.out.println("------OSS文件上传成功------" + fileUrl);
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return FILE_URL;
	}

	/**
	 * S3 文件上传成功,返回文件完整访问路径 文件上传失败,返回 null
	 *
	 * @param file    待上传文件
	 * @param fileDir 文件保存目录
	 * @return oss 中的相对文件路径
	 */
	public static String upload(FileItemStream file, String fileDir) {
		initS3(endPoint, accessKeyId, accessKeySecret);
		StringBuilder fileUrl = new StringBuilder();
		try {
			String suffix = file.getName().substring(file.getName().lastIndexOf('.'));
			String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
			if (!fileDir.endsWith("/")) {
				fileDir = fileDir.concat("/");
			}
			fileUrl = fileUrl.append(fileDir + fileName);

			if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
				FILE_URL = staticDomain + "/" + fileUrl;
			} else {
				FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
			}
			PutObjectResult result = s3Client.putObject(bucketName, fileUrl.toString(), file.openStream(), new ObjectMetadata());
			// 设置权限(公开读)
			s3Client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
			if (result != null) {
				System.out.println("------S3文件上传成功------" + fileUrl);
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return FILE_URL;
	}

	/**
	 * 删除文件
	 * 
	 * @param url
	 */
	public static void deleteUrl(String url) {
		String bucketUrl = "https://" + bucketName + "." + endPoint + "/";
		// String bucketUrl = staticDomain + "/";
		url = url.replace(bucketUrl, "");
		s3Client.deleteObject(bucketName, url);
	}

	/**
	 * 删除文件
	 * 
	 * @param fileName
	 */
	public static void delete(String fileName) {
		s3Client.deleteObject(bucketName, fileName);
	}

	public static S3ObjectInputStream download(String fileName) {
		initS3(endPoint, accessKeyId, accessKeySecret);
		S3Object o = s3Client.getObject(bucketName, fileName);
		S3ObjectInputStream s3is = o.getObjectContent();
		return s3is;
	}

	/**
	 * 初始化 AmazonS3 客户端
	 *
	 * @return
	 */
	private static AmazonS3 initS3(String endpoint, String accessKeyId, String accessKeySecret) {
		if (s3Client == null) {
			BasicAWSCredentials credentials = new BasicAWSCredentials(accessKeyId, accessKeySecret);
			ClientConfiguration clientConfig = new ClientConfiguration();
			s3Client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials)).withClientConfiguration(clientConfig).withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, "cn")).withPathStyleAccessEnabled(true).build();
		}
		return s3Client;
	}

}

CommonController.java

package org.jeecg.common.system.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.model.S3ObjectInputStream;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@RestController
@RequestMapping("/sys/common")
public class CommonController {



	/**
	 * 文件上传统一方法
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@PostMapping(value = "/upload")
	public Result<?> upload(HttpServletRequest request, HttpServletResponse response) {
		Result<?> result = new Result<>();
		String savePath = "";
		String bizPath = request.getParameter("biz");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
		if (oConvertUtils.isEmpty(bizPath)) {
			if (CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)) {
				result.setMessage("使用阿里云文件上传时,必须添加目录!");
				result.setSuccess(false);
				return result;
			} else {
				bizPath = "";
			}
		}
		if (CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)) {
			savePath = this.uploadLocal(file, bizPath);
		} else {
			savePath = sysBaseAPI.upload(file, bizPath, uploadType);
		}
		if (oConvertUtils.isNotEmpty(savePath)) {
			result.setMessage(savePath);
			result.setSuccess(true);
		} else {
			result.setMessage("上传失败!");
			result.setSuccess(false);
		}
		return result;
	}

	/**
	 * 本地文件上传
	 * 
	 * @param mf      文件
	 * @param bizPath 自定义路径
	 * @return
	 */
	private String uploadLocal(MultipartFile mf, String bizPath) {
		try {
			String ctxPath = uploadpath;
			String fileName = null;
			File file = new File(ctxPath + File.separator + bizPath + File.separator);
			if (!file.exists()) {
				file.mkdirs();// 创建文件根目录
			}
			String orgName = mf.getOriginalFilename();// 获取文件名
			fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
			String savePath = file.getPath() + File.separator + fileName;
			File savefile = new File(savePath);
			FileCopyUtils.copy(mf.getBytes(), savefile);
			String dbpath = null;
			if (oConvertUtils.isNotEmpty(bizPath)) {
				dbpath = bizPath + File.separator + fileName;
			} else {
				dbpath = fileName;
			}
			if (dbpath.contains("\\")) {
				dbpath = dbpath.replace("\\", "/");
			}
			return dbpath;
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
		return "";
	}


	@GetMapping(value = "/static/**")
	public void view(HttpServletRequest request, HttpServletResponse response) {
		OutputStream outputStream = null;
		String imgPath = extractPathFromPattern(request);
		String fileName = imgPath.substring(imgPath.lastIndexOf("/")+1);
		S3ObjectInputStream s3is = sysBaseAPI.download(imgPath);
		try {
			response.setContentType("application/force-download");// 设置强制下载不打开
			response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("UTF-8"), "iso-8859-1"));
			outputStream = response.getOutputStream();
			byte[] read_buf = new byte[1024];
			int read_len = 0;
			while ((read_len = s3is.read(read_buf)) > 0) {
				outputStream.write(read_buf, 0, read_len);
			}
			response.flushBuffer();
		} catch (AmazonServiceException e) {
			log.error("预览文件失败" + e.getMessage());
		} catch (FileNotFoundException e) {
			log.error("预览文件失败" + e.getMessage());
		} catch (IOException e) {
			log.error("预览文件失败" + e.getMessage());
		} finally {
			if (s3is != null) {
				try {
					s3is.close();
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
			}
		}
	}

	/**
	 * @功能:pdf预览Iframe
	 * @param modelAndView
	 * @return
	 */
	@RequestMapping("/pdf/pdfPreviewIframe")
	public ModelAndView pdfPreviewIframe(ModelAndView modelAndView) {
		modelAndView.setViewName("pdfPreviewIframe");
		return modelAndView;
	}

	/**
	 * 把指定URL后的字符串全部截断当成参数 这么做是为了防止URL中包含中文或者特殊字符(/等)时,匹配不了的问题
	 * 
	 * @param request
	 * @return
	 */
	private static String extractPathFromPattern(final HttpServletRequest request) {
		String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
		String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
		return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
	}

}

 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值