java aliyun oss上传和下载工具类
依赖
<dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.8.0</version></dependency>
工具类
import com.alibaba.fastjson.JSON;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Objects;
import java.util.UUID;@Component
@Slf4j
public class OssUtil {@Value("${aa.endpoint}")private String endpoint;@Value("${aa.accessKeyId}")private String accessKeyId;@Value("${aa.accessKeySecret}")private String accessKeySecret;@Value("${aa.bucketName}")private String bucketName;@Value("${aa.callbackPath}")private String callbackPath;public String uploadSingleFile(File file, String fileName) {String uploadedFileUrl = "";OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);PutObjectRequest putObjectRequest = new PutObjectRequest("plant-device", fileName, file);PutObjectResult result = ossClient.putObject(putObjectRequest);System.out.println("Ali-Oss-PutObjectResult --->" + JSON.toJSONString(result));if (null != result && StringUtils.isNotBlank(result.getETag())) {uploadedFileUrl = callbackPath + "/" + fileName;}ossClient.shutdown();return uploadedFileUrl;}public void downloadFile(String filename, HttpServletResponse response) throws Exception {ServletOutputStream out =null;ByteArrayOutputStream baos = null;InputStream inputStream = null;OSS ossClient = null;String encodeFileName = URLEncoder.encode(filename);try{ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, filename, HttpMethod.GET);request.setExpiration(expiration);URL signedUrl = ossClient.generatePresignedUrl(request);OSSObject ossObject = ossClient.getObject(signedUrl, new HashMap<>());if (ossObject != null) {inputStream = ossObject.getObjectContent();out = response.getOutputStream();byte[] buffer = new byte[1024];int len;baos = new ByteArrayOutputStream();while ((len=inputStream.read(buffer))!=-1){baos.write(buffer,0,len);}response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");response.addHeader("Content-Disposition", "attachment;filename=\"" + encodeFileName+"\"");response.addHeader("Content-Length", "" + baos.size());response.setHeader("filename", "\"" + encodeFileName+"\"");response.setContentType("application/octet-stream");out.write(baos.toByteArray());}}catch (Exception e){e.printStackTrace();log.error("downloadFile error:"+e.getMessage());throw e;}finally {try{if(null!= baos){baos.flush();}if(null!= out){out.flush();}if(null!= response){response.flushBuffer();}if(null!= baos){baos.close();}if(null!= out){out.close();}if(null!= ossClient){ossClient.shutdown();}}catch (Exception e){e.printStackTrace();log.error(e.getMessage());}}}public String uploadSingleFile(MultipartFile file, InputStream instream) {long dd1 = new Date().getTime();if (Objects.isNull(file)) {return null;}try {String fileName = file.getOriginalFilename().replaceAll(" ", "");log.info("===========" + fileName);String fileTyle = fileName.substring(fileName.lastIndexOf("."), fileName.length());System.out.println(fileTyle);fileName = UUID.randomUUID().toString().replaceAll("-", "") + fileTyle;OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);ossClient.putObject(bucketName, fileName, instream);Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 100);URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);ossClient.shutdown();instream.close();long dd2 = new Date().getTime();System.out.println("========OSS 相应时间=======" + ((dd1 - dd2) / 1000) + "秒========");return callbackPath + "/" + URLEncoder.encode(fileName, "UTF-8");} catch (Exception e) {e.printStackTrace();} finally {try {if (instream != null) {instream.close();}} catch (IOException e) {e.printStackTrace();}}return null;}}