阿里云OSS对象存储实现文件的上传,并返回访问路径

话不多说,直接上干货

官方文档:https://help.aliyun.com/product/31815.html?spm=a2c4g.11186623.6.540.539d28bca7ZyUR

1.首先引入pom依赖

		<dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.8.0</version>
        </dependency>

2.文件上传代码

Controller层:

	 public String upload(MultipartFile file){
		return fileUploadService.upload(file);
	 }

Service层:

    String upload(MultipartFile multipartFile);

ServiceImpl层:

	@Override
    public String upload(MultipartFile multipartFile){
	   
		// 定义你的BucketName
		String bucketName = "";

        String fileAllName = multipartFile.getOriginalFilename();
        String fileType = fileAllName.substring(fileAllName.lastIndexOf(".") + 1);
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        filePath = filePath + "/" +uuid +"."+fileType;
        String url=endpoint.replaceFirst("http://","http://"+bucketName +".")+"/"+filePath; 
        String contentType = OssUtils.getContentType(fileAllName);
        //保存本地
        File file = XmlUtil.ossUpload(multipartFile);
        try {
            //上传oss
            OssUtils.ossUpload(filePath, file,contentType);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("上传失败");
        }
        //删除本地文件
        XmlUtil.deleteFile(file);
        return url;
  }

3.工具类

3.1 OssUtils:


public class OssUtils {
	
	// 创建存储空间,Endpoint以杭州为例,其它Region请按实际情况填写。
    private String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    private String accessId = "";
    private String accessKey = "";
    private String privateDomain = "";
    private String privateBucket = "";

  
   public void ossUpload(String fileName, File file, String contentType) {
        try {
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentType(contentType);
            UploadFileRequest uploadFileRequest = new UploadFileRequest(privateBucket, fileName);
            // 指定上传的本地文件。
            uploadFileRequest.setUploadFile(file.toString());
            // 指定上传并发线程数,默认为1。
            uploadFileRequest.setTaskNum(5);
            // 指定上传的分片大小,范围为100KB~5GB,默认为文件大小/10000。
            uploadFileRequest.setPartSize(1 * 1024 * 1024);
            // 开启断点续传,默认关闭。
            uploadFileRequest.setEnableCheckpoint(true);
            uploadFileRequest.setCheckpointFile("uploadFile.ucp");
            // 文件的元数据。
            uploadFileRequest.setObjectMetadata(meta);
            // 设置上传成功回调,参数为Callback类型。
            //uploadFileRequest.setCallback("");
            // 断点续传上传。
            ossClient.uploadFile(uploadFileRequest);
            // 关闭OSSClient。
            ossClient.shutdown();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }


    /**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     */
    public String getContentType(String fileName) {
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if (".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        }
        if (".jpg".equalsIgnoreCase(fileExtension)) {
            return "image/jpg";
        }
        if (".png".equalsIgnoreCase(fileExtension)) {
            return "image/png";
        }
        if (".html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        if (".mp4".equalsIgnoreCase(fileExtension)) {
            return "video/mp4";
        }
        if (".mp3".equalsIgnoreCase(fileExtension)) {
            return "audio/mp3";
        }
        return "text/html";
    }
}

3.2 XmlUtil:

public class XmlUtil {

   
    public static void deleteFile(File... files) {
            for (File file : files) {
                //logger.info("File:[{}]",file.getAbsolutePath());
                if (file.exists()) {
                    file.delete();
                }
            }
    }

    public static File ossUpload(MultipartFile file) throws IOException {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 用uuid作为文件名,防止生成的临时文件重复
        File excelFile = File.createTempFile(UUID.randomUUID().toString(), prefix);
        // MultipartFile to File
        file.transferTo(excelFile);
        //程序结束时,删除临时文件
        return excelFile;
    }
}

PS: 没有写概念类的东西,建议看之前先看看官网文档哦,然后就能看懂代码啦,小伙伴们加油哦

你可能感兴趣的:(阿里云产品,java,阿里云,spring)