记录代码,如有错误,希望大家能够指出问题。
官网地址:
对象存储 OSS - 帮助中心 - 阿里云.html
阿里云对象存储OSS(Object Storage Service)是一款海量、安全、低成本、高可靠的云存储服务,可提供99.9999999999%(12个9)的数据持久性,99.995%的数据可用性。多种存储类型供选择,全面优化存储成本。
OSS具有与平台无关的RESTful API接口,您可以在任何应用、任何时间、任何地点存储和访问任意类型的数据。
您可以使用阿里云提供的API、SDK接口或者OSS迁移工具轻松地将海量数据移入或移出阿里云OSS。数据存储到阿里云OSS以后,您可以选择标准存储(Standard)作为移动应用、大型网站、图片分享或热点音视频的主要存储方式,也可以选择成本更低、存储期限更长的低频访问存储(Infrequent Access)、归档存储(Archive)、冷归档存储(Cold Archive)作为不经常访问数据的存储方式。
以上摘录官网。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=".0.0" xmlns:xsi=""xsi:schemaLocation=".0.0 .0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.4.1</version><relativePath/> <!-- lookup parent from repository --></parent><groupId&le</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><name>demo</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.10.2</version></dependency><dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-core</artifactId><version>[4.4.9,5.0.0)</version></dependency><dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-imm</artifactId><optional>true</optional><version>1.22.0</version></dependency><dependency><groupId&le.code.gson</groupId><artifactId>gson</artifactId><version>2.8.5</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.3</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.5</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId&batis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.2</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.10</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.28</version><scope>runtime</scope></dependency></dependencies></project>
ller;import com.del.ObjectListing;
fig.OSSProperties;
ample.demo.utils.OSSUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@RestController
public class uploadPhoto {@RequestMapping("/hello")public String helloWorld() {return "nihao";}/*** 多图片上传** @param fileList* @return*/@RequestMapping("/uploads")public String checkList(List<MultipartFile> fileList) {String photoUrl = "";OSSUtil ossClient = new OSSUtil();try {for (int i = 0; i < fileList.size(); i++) {//将文件上传String name = ossClient.(i));//获取文件的URl地址 以便前台 显示String imgUrl = ImgUrl(name);if (i == 0) {photoUrl = imgUrl;} else {photoUrl += "," + imgUrl;}}} catch (Exception e) {e.printStackTrace();}im();}/*** 单文件上传** @param imgFile* @param req* @return* @throws Exception*/@RequestMapping("/upload")public Map<String, Object> uploadPhoto(@RequestParam("imgFile") MultipartFile imgFile, HttpServletRequest req) {OSSUtil ossClient = new OSSUtil();Map<String, Object> m = new HashMap<>();if (imgFile.isEmpty()) {m.put("error", "上传文件不能为空");}String newsUrl = "";if (!(imgFile).isEmpty()) {try {//将文件上传String name = ossClient.uploadImg2Oss(imgFile);//获取文件的URl地址 以便前台 显示String imgUrl = ImgUrl(name);m.put("url", imgUrl);} catch (IOException e) {e.printStackTrace();}} else {m.put("error", "上传图片不可为空");}return m;}/*** 获取oss文件** @param key* @return*/@RequestMapping("/onlineSee")public Map<String, Object> onlineSee(String key) {OSSUtil ossClient = new OSSUtil();Map<String, Object> m = new HashMap<>();String strings = lineSee(key);m.put("url", strings);return m;}/*** 文档预览** @param key* @return*/@RequestMapping("/onlinePreview")public Map<String, Object> onlinePreview(String key) {OSSUtil ossClient = new OSSUtil();Map<String, Object> m = new HashMap<>();Object strings = linePreview(key);m.put("url", strings);return m;}/*** 获取文件** @param key* @return*/@RequestMapping("/getUrl")public Map<String, Object> getUrl(String key) {OSSUtil ossClient = new OSSUtil();Map<String, Object> m = new HashMap<>();String strings = Url(key);m.put("url", strings);return m;}/*** 获取文件夹** @param fileName* @return*/@RequestMapping("/fileFolder")public Map<String, Object> fileFolder(String fileName) {Map<String, Object> m = new HashMap<>();OSSUtil ossClient = new OSSUtil();List<String> strings = ossClient.fileFolder(fileName);m.put("fileFolder", strings);return m;}/*** 通过文件名下载文件** @param objectName* @param localFileName* @return*/@RequestMapping(value = "/downloadFile", method = RequestMethod.GET)public void downloadFile( HttpServletResponse response, String objectName, String localFileName) {try {OSSUtil ossClient = new OSSUtil();ossClient.downloadFile(response, objectName, localFileName);} catch (Exception e) {e.printStackTrace();}}/*** 删除文件** @param key* @return*/@RequestMapping(value = "/deleteObject", method = RequestMethod.POST)public void deleteObject(String key) {try {OSSUtil ossClient = new OSSUtil();ossClient.delFile(key);} catch (Exception e) {e.printStackTrace();}}/*** 获取文件夹下文件列表** @param fileHost* @return*/@RequestMapping("/listFile")public Map<String, Object> listFile(String fileHost, String nextMarker) {OSSUtil ossClient = new OSSUtil();Map<String, Object> m = new HashMap<>();List<String> strings = ossClient.listFile(fileHost, nextMarker);m.put("listFile", strings);return m;}/*** 获取文件夹下文件列表和文件夹** @param fileHost* @return*/@RequestMapping("/listFile2")public Map<String, Object> listFile2(String fileHost, String nextMarker) {OSSUtil ossClient = new OSSUtil();Map<String, Object> m = new HashMap<>();ObjectListing strings = ossClient.listFile2(fileHost, nextMarker);m.put("listFile", strings);return m;}/*** 创建文件夹** @param folder* @return*/@RequestMapping("/createFolder")public Map<String, Object> createFolder(String folder) {Map<String, Object> m = new HashMap<>();try {OSSUtil ossClient = new OSSUtil();String reFolder = ateFolder(folder);m.put("reFolder", reFolder);} catch (Exception e) {e.printStackTrace();m.put("error", "请输入文件名");}return m;}/*** 后台提供获取secretAccessKey,accessKeyId接口** @param* @return*/@RequestMapping("/ossConfig")public Map<String, Object> ossConfig() {Map<String, Object> m = new HashMap<>();try {String aliyunAccessKey = OSSProperties.ALIYUN_ACCESS_KEY;String aliyunAccessId = OSSProperties.ALIYUN_ACCESS_ID;m.put("aliyunAccessKey", aliyunAccessKey);m.put("aliyunAccessId", aliyunAccessId);} catch (Exception e) {e.printStackTrace();}return m;}}
ample.demo.utils;import com.alibaba.druid.util.StringUtils;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.del.*;
fig.OSSProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.URL;
import java.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;public class OSSUtil {/*** log日志*/public static final Logger logger = Logger(OSSUtil.class);private static final String endpoint = OSSProperties.ALIYUN_ENDPOINT;private static final String accessKeyId = OSSProperties.ALIYUN_ACCESS_ID;private static final String accessKeySecret = OSSProperties.ALIYUN_ACCESS_KEY;private static final String bucketName = OSSProperties.ALIYUN_BUCKET;private static final String FOLDER = OSSProperties.ALIYUN_DIR;/*** 获取oss** @return*/public static OSS getOSSClient() {return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);}/*** 上传图片** @param url* @throws*/public void uploadImg2Oss(String url) throws IOException {File fileOnServer = new File(url);FileInputStream fin;try {fin = new FileInputStream(fileOnServer);String[] split = url.split("/");this.uploadFile2OSS(fin, split[split.length - 1]);} catch (FileNotFoundException e) {throw new IOException("图片上传失败");}}public String uploadImg2Oss(MultipartFile file) throws IOException {/* if (Size() > 10 * 1024 * 1024) {throw new IOException("上传图片大小不能超过10M!");}*/String originalFilename = OriginalFilename();String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();Random random = new Random();String name = Int(10000) + System.currentTimeMillis() + substring;System.out.println(System.currentTimeMillis());System.out.println(name);System.out.Int(10000));
// name = DateUtils.dateStr(new Date(), "yyyy/MM/dd") + "/" + System.currentTimeMillis() + substring;try {InputStream inputStream = InputStream();this.uploadFile2OSS(inputStream, name);return name;} catch (Exception e) {e.printStackTrace();throw new IOException("图片上传失败");}}/*** 获得图片路径** @param fileUrl* @return*/public String getImgUrl(String fileUrl) {System.out.println(fileUrl);if (!StringUtils.isEmpty(fileUrl)) {String[] split = fileUrl.split("/");Url(this.FOLDER + split[split.length - 1]);}return "";}/*** 上传到OSS服务器 如果同名文件会覆盖服务器上的** @param instream 文件流* @param fileName 文件名称 包括后缀名* @return 出错返回"" ,唯一MD5数字签名*/public String uploadFile2OSS(InputStream instream, String fileName) {String ret = "";try {OSS ossClient = getOSSClient();// 创建上传Object的MetadataObjectMetadata objectMetadata = new ObjectMetadata();objectMetadata.setContentLength(instream.available());objectMetadata.setCacheControl("no-cache");objectMetadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));objectMetadata.setHeader("Pragma", "no-cache");
// objectMetadata.setContentDisposition("inline;filename=" + fileName);// 上传文件PutObjectResult putResult = ossClient.putObject(bucketName, FOLDER + fileName, instream, objectMetadata);ret = ETag();} catch (IOException e) {(e.getMessage(), e);} finally {try {if (instream != null) {instream.close();}} catch (IOException e) {e.printStackTrace();}}return ret;}/*** 通过文件名判断并获取OSS服务文件上传时文件的contentType** @param filenameExtension 文件名* @return 文件的contentType*/public static final String getContentType(String filenameExtension) {if (filenameExtension.equalsIgnoreCase(".bmp")) {return "application/x-bmp";}if (filenameExtension.equalsIgnoreCase(".gif")) {return "image/gif";}if (filenameExtension.equalsIgnoreCase(".jpeg") ||filenameExtension.equalsIgnoreCase(".jpg") ||filenameExtension.equalsIgnoreCase(".png")) {return "image/jpg";}if (filenameExtension.equalsIgnoreCase(".html")) {return "text/html";}if (filenameExtension.equalsIgnoreCase(".txt")) {return "text/plain";}if (filenameExtension.equalsIgnoreCase(".vsd")) {return "application/vnd.visio";}if (filenameExtension.equalsIgnoreCase(".pptx") ||filenameExtension.equalsIgnoreCase(".ppt")) {return "application/vnd.ms-powerpoint";}if (filenameExtension.equalsIgnoreCase(".docx") ||filenameExtension.equalsIgnoreCase(".doc")) {return "application/msword";}if (filenameExtension.equalsIgnoreCase(".xla") ||filenameExtension.equalsIgnoreCase(".xlc") ||filenameExtension.equalsIgnoreCase(".xlm") ||filenameExtension.equalsIgnoreCase(".xls") ||filenameExtension.equalsIgnoreCase(".xlt") ||filenameExtension.equalsIgnoreCase(".xlw")) {return "application/vnd.ms-excel";}if (filenameExtension.equalsIgnoreCase(".xlsx")) {return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";}if (filenameExtension.equalsIgnoreCase(".xml")) {return "text/xml";}if (filenameExtension.equalsIgnoreCase(".pdf")) {return "application/pdf";}if (filenameExtension.equalsIgnoreCase(".zip")) {return "application/zip";}if (filenameExtension.equalsIgnoreCase(".tar")) {return "application/x-tar";}if (filenameExtension.equalsIgnoreCase(".avi")) {return "video/avi";}if (filenameExtension.equalsIgnoreCase(".mp4")) {return "video/mpeg4";}if (filenameExtension.equalsIgnoreCase(".mp3")) {return "audio/mp3";}if (filenameExtension.equalsIgnoreCase(".mp2")) {return "audio/mp2";}// 默认下载
// return "application/octet-stream";return "image/jpg";}/*** 获得url链接** @param key* @return*/public String getUrl(String key) {// 设置URL过期时间为10年 3600l* 1000*24*365*10OSS ossClient = getOSSClient();Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);// 生成URLURL url = atePresignedUrl(bucketName, key, expiration);if (url != null) {String host = "" + Host() + Path();return host;}return "";}/*** 获取文件夹** @param fileName* @return*/public List<String> fileFolder(String fileName) {// 创建OSSClient实例。OSS ossClient = getOSSClient();// 构造ListObjectsRequest请求。ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);// 设置正斜线(/)为文件夹的分隔符。listObjectsRequest.setDelimiter("/");// 设置prefix参数来获取fun目录下的所有文件。if (!StringUtils.isEmpty(fileName)) {listObjectsRequest.setPrefix(fileName + "/");}// 列出文件ObjectListing listing = ossClient.listObjects(listObjectsRequest);// 遍历所有commonPrefixList<String> list = new ArrayList<>();for (String commonPrefix : CommonPrefixes()) {String newCommonPrefix = commonPrefix.substring(0, commonPrefix.length() - 1);String[] s = newCommonPrefix.split("/");if (!StringUtils.isEmpty(fileName)) {list.add(s[s.length - 1]);} else {list.add(s[0]);}}// 关闭OSSClientossClient.shutdown();return list;}/*** 列举文件下所有的文件url信息*/public ObjectListing listFile2(String fileHost, String nextMarker) {// 创建OSSClient实例。OSS ossClient = getOSSClient();// 构造ListObjectsRequest请求。ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);// 设置正斜线(/)为文件夹的分隔符。listObjectsRequest.setDelimiter("/");// 列出fun目录下的所有文件和文件夹。listObjectsRequest.setPrefix(fileHost + "/");ObjectListing listing = ossClient.listObjects(listObjectsRequest);// 遍历所有文件。System.out.println("Objects:");// objectSummaries的列表中给出的是fun目录下的文件。for (OSSObjectSummary objectSummary : ObjectSummaries()) {System.out.Key());}// 遍历所有commonPrefix。System.out.println("nCommonPrefixes:");// commonPrefixs列表中显示的是fun目录下的所有子文件夹。由于fun/movie/001.avi和fun/movie/007.avi属于fun文件夹下的movie目录,因此这两个文件未在列表中。for (String commonPrefix : CommonPrefixes()) {System.out.println(commonPrefix);}// 关闭OSSClient。ossClient.shutdown();return listing;}/*** 列举文件下所有的文件url信息*/public List<String> listFile(String fileHost, String nextMarker) {// 创建OSSClient实例。OSS ossClient = getOSSClient();// 构造ListObjectsRequest请求ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);// 设置prefix参数来获取fun目录下的所有文件。listObjectsRequest.setPrefix(fileHost + "/");listObjectsRequest.setMarker(nextMarker);// 列出文件。ObjectListing listing = ossClient.listObjects(listObjectsRequest);// 遍历所有文件。List<String> list = new ArrayList<>();for (int i = 0; i < ObjectSummaries().size(); i++) {String FILE_URL = "" + bucketName + "." + endpoint + "/" + ObjectSummaries().get(i).getKey();list.add(FILE_URL);}// 关闭OSSClient。ossClient.shutdown();// ObjectListing objectListing = null;
// int total = 0;
// HashMap<Integer, String> markerMap = new HashMap<>();
// try {
// ObjectListing objectListing2 = null;
// do {
// String nextMarker2 = objectListing2 != null ? NextMarker() : null;
// ListObjectsRequest listObjectsRequest2 = new ListObjectsRequest(bucketName).withMarker(nextMarker2).withMaxKeys(100);
// listObjectsRequest2.setPrefix(fileHost + "/");
// objectListing2 = ossClient.listObjects(listObjectsRequest2);
// total += (objectListing2 != null && ObjectSummaries() != null ? ObjectSummaries().size() : 0);
// markerMap.put(markerMap.size() + 1, nextMarker2);
// } while (objectListing2 != null && !StringUtils.NextMarker()));
//
// ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName).withMarker(nextMarker).withMaxKeys(100);
//
// listObjectsRequest.setPrefix(fileHost + "/");
//
// objectListing = ossClient.listObjects(listObjectsRequest);
// for (int i = 0; i < ObjectSummaries().size(); i++) {
// String FILE_URL = "" + bucketName + "." + endpoint + "/" + ObjectSummaries().get(i).getKey();
// list.add(FILE_URL);
// }
//
// } catch (Exception e) {
//
// } finally {
// // 关闭client
// ossClient.shutdown();
// }return list;}/*** 删除文件* objectName key 地址** @param filePath*/public Boolean delFile(String filePath) {// 创建OSSClient实例。OSS ossClient = getOSSClient();// 删除Object.boolean exist = ossClient.doesObjectExist(bucketName, filePath);if (!exist) {return false;}ossClient.deleteObject(bucketName, filePath);ossClient.shutdown();return true;}/*** 批量删除** @param keys*/public Boolean delFileList(List<String> keys) {// 创建OSSClient实例。OSS ossClient = getOSSClient();try {// 删除文件。DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys));List<String> deletedObjects = DeletedObjects();} catch (Exception e) {e.printStackTrace();return false;} finally {ossClient.shutdown();}return true;}/*** 创建文件夹** @param folder* @return*/public String createFolder(String folder) {// 创建OSSClient实例。OSS ossClient = getOSSClient();// 文件夹名final String keySuffixWithSlash = folder;// 判断文件夹是否存在,不存在则创建if (!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)) {// 创建文件夹ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));// 得到文件夹名OSSObject object = Object(bucketName, keySuffixWithSlash);String fileDir = Key();ossClient.shutdown();return fileDir;}return keySuffixWithSlash;}/*** 通过文件名下载文件** @param objectName 要下载的文件名* @param localFileName 本地要创建的文件名*/public void downloadFile(HttpServletResponse response, String objectName, String localFileName) throws Exception {// 创建OSSClient实例。OSS ossClient = getOSSClient();try {// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。OSSObject ossObject = Object(bucketName, objectName);// 读去Object内容 返回BufferedInputStream in = new ObjectContent());BufferedOutputStream out = new OutputStream());//通知浏览器以附件形式下载response.setHeader("Content-Disposition", "attachment;filename=" + de(objectName, "utf-8"));//BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(new File("f:\a.txt")));byte[] car = new byte[1024];int L = 0;while ((L = in.read(car)) != -1) {out.write(car, 0, L);}if (out != null) {out.flush();out.close();}if (in != null) {in.close();}} catch (Exception e) {e.printStackTrace();} finally {// 关闭OSSClient。ossClient.shutdown();}}public String onlineSee(String key) {// 创建OSSClient实例。OSS ossClient = getOSSClient();// 设置URL过期时间为1小时Date expiration = new Date(new Date().getTime() + 3600 * 1000);// 临时地址URL url = atePresignedUrl(bucketName, key, expiration);// 关闭OSSClient。ossClient.shutdown();String();}public Object onlinePreview(String key) {// 创建OSSClient实例。OSS ossClient = getOSSClient();// 设置视频截帧操作。文档页数默认是200,EndPage_-1任意String style = "imm/previewdoc,EndPage_-1";String filenameExtension = key.substring(key.lastIndexOf("."));if (filenameExtension.equalsIgnoreCase(".pdf")) {style = "imm/previewdoc,EndPage_-1,PdfVector_true";}// 指定过期时间为1小时。Date expiration = new Date(new Date().getTime() + 1000 * 60 * 60);GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, key, HttpMethod.GET);req.setExpiration(expiration);req.setProcess(style);URL signedUrl = atePresignedUrl(req);return signedUrl;}public static void main(String[] args) {}}
fig;import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import t.annotation.PropertySource;
import org.springframework.stereotype.Component;@Component
@PropertySource("classpath:/aliyun.properties")
public class OSSProperties implements InitializingBean {@Value("${dpoint}")private String aliyun_endpoint;@Value("${aliyun.access-id}")private String aliyun_access_id;@Value("${aliyun.access-key}")private String aliyun_access_key;@Value("${aliyun.bucket}")private String aliyun_bucket;@Value("${aliyun.dir}")private String aliyun_dir;//声明静态变量,public static String ALIYUN_ENDPOINT;public static String ALIYUN_ACCESS_ID;public static String ALIYUN_ACCESS_KEY;public static String ALIYUN_BUCKET;public static String ALIYUN_DIR;@Overridepublic void afterPropertiesSet() throws Exception {ALIYUN_ENDPOINT = aliyun_endpoint;ALIYUN_ACCESS_ID = aliyun_access_id;ALIYUN_ACCESS_KEY = aliyun_access_key;ALIYUN_BUCKET = aliyun_bucket;ALIYUN_DIR = aliyun_dir;}
}
aliyun.access-id=
aliyun.access-key=
aliyun.bucket=
dpoint=
aliyun.dir=
本文发布于:2024-01-29 15:36:35,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170651379716292.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |