java上传阿里云oss

文章目录

      • 第一步 pom.xml引入
      • 第二步 在application.yml中添加
      • 第三步 在util包下面创建OssUtil
      • 第四步 在Controller层创建OssController类
      • 前端上传

第一步 pom.xml引入

   
        
            com.aliyun.oss
            aliyun-sdk-oss
            3.6.0
        



第二步 在application.yml中添加

aliyun:
  oss:
    bucketName: 你的bucket名字
    endpoint: oss-cn-chengdu.aliyuncs.com
    accessKeyId: 你的keyid
    accessKeySecret: 你的secret




第三步 在util包下面创建OssUtil

package com.hailan.hailan.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

/**
 * 阿里云OSS服务器工具类
 */
@Component
public class OssUtil {

    //---------变量----------
    protected static final Logger log = LoggerFactory.getLogger(OssUtil.class);

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    //文件存储目录
        private String filedir = "MyFile/";

    /**
     * 1、单个文件上传
     * @param file
     * @return 返回完整URL地址
     */
    public String uploadFile(MultipartFile file) {
        String fileUrl = uploadImg2Oss(file);
        String str = getFileUrl(fileUrl);
        return  str.trim();
    }

    /**
     * 1、单个文件上传(指定文件名(带后缀))
     * @param file
     * @return 返回完整URL地址
     */
    public String uploadFile(MultipartFile file,String fileName) {
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, fileName);
            return fileName;
        }
        catch (Exception e) {
            return "上传失败";
        }
    }

    /**
     * 2、多文件上传
     * @param fileList
     * @return 返回完整URL,逗号分隔
     */
    public String uploadFile(List fileList) {
        String  fileUrl = "";
        String  str = "";
        String  photoUrl = "";
        for(int i = 0;i< fileList.size();i++){
            fileUrl = uploadImg2Oss(fileList.get(i));
            str = getFileUrl(fileUrl);
            if(i == 0){
                photoUrl = str;
            }else {
                photoUrl += "," + str;
            }
        }
        return photoUrl.trim();
    }

    /**
     * 3、通过文件名获取文完整件路径
     * @param fileUrl
     * @return 完整URL路径
     */
    public String getFileUrl(String fileUrl) {
        if (fileUrl !=null && fileUrl.length()>0) {
            String[] split = fileUrl.split("/");
            String url =  this.getUrl(this.filedir + split[split.length - 1]);
            return url;
        }
        return null;
    }

    //获取去掉参数的完整路径
    private String getShortUrl(String url) {
        String[] imgUrls = url.split("\\?");
        return imgUrls[0].trim();
    }

    // 获得url链接
    private String getUrl(String key) {
        // 设置URL过期时间为20年  3600l* 1000*24*365*20
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 20);
        // 生成URL
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return  getShortUrl(url.toString());
        }
        return null;
    }

    // 上传文件
    private String uploadImg2Oss(MultipartFile file) {
        //1、限制最大文件为1G
        if (file.getSize() > 1024 * 1024 * 1024) {
            return "文件太大";
        }

        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase(); //文件后缀
        String uuid = UUID.randomUUID().toString();
        String name = uuid + suffix;

        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, name);
            return name;
        }
        catch (Exception e) {
            return "上传失败";
        }
    }


    // 上传文件(指定文件名)
    private String uploadFile2OSS(InputStream instream, String fileName) {
        String ret = "";
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cossClientache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件

            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
            ret = putResult.getETag();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * 删除某个Object
     *
     * @param bucketUrl
     * @return
     */
    public boolean deleteObject(String bucketUrl) {
          bucketUrl = bucketUrl.substring(bucketUrl.lastIndexOf(filedir));
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            // 删除Object.
            client.deleteObject(bucketName, bucketUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            client.shutdown();
        }
        return true;
    }

    /**
     * 删除多个Object
     *
     * @param bucketUrls
     * @return
     */
    public boolean deleteObjects(List bucketUrls) {
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            // 删除Object.
            DeleteObjectsResult deleteObjectsResult = client.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(bucketUrls));
            List deletedObjects = deleteObjectsResult.getDeletedObjects();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            client.shutdown();
        }
        return true;
    }


    private static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpeg";
        }
        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(".xml")) {
            return "text/xml";
        }
        //PDF
        if (FilenameExtension.equalsIgnoreCase(".pdf"))  {
            return "application/pdf";
        }
        return "image/jpeg";
    }

    public static void main(String[] args) {

       OssUtil o = new OssUtil();
       //http://dqva.oss-cn-beijing.aliyuncs.com/
        String bucketUrl = "http://dqva.oss-cn-beijing.aliyuncs.com/my_file/706491db-4fde-4d9c-9a91-ef929d53a45c.jpg";
        String url = bucketUrl.substring(bucketUrl.lastIndexOf("my_file"));
        System.out.println(url);

//        boolean b = o.deleteObject( "my_file/706491db-4fde-4d9c-9a91-ef929d53a45c.jpg");
//        System.out.println(b);

        //下载
//        String urllink = "https://shenlin.oss-cn-beijing.aliyuncs.com/my_file/ce176d37-dbba-4f2b-8b9c-4c76d0316274.jpg  GE8LASyBUExjxPyLFfpmTs&Signature=F96dQ2zCdTPG66PlbQgpGxec34U%3D&versionId=CAEQAhiBgIC.nJm0vBciIDYwOTdmYjIzOGFhNjRhYTI5ZTgzMTRmZTE2YTlmMDlh&response-content-type=application%2Foctet-stream";
//
//        method1(urllink);
    }
    //----下载---------
    public static void method1(String urllink){


        System.out.println("下载1");
        try {
            URL url = new URL(urllink);
            //打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream。
            InputStream in = url.openStream();
            download(in);
            System.out.println("下载2");
        } catch (IOException e){

        }
    }
    public static void download(InputStream inputStream){

        try {

            System.out.println("下载3");
            File file = new File("D:\\A.jpg");
            OutputStream outputStream = new FileOutputStream(file);

            int byteCount = 0;
            //1M逐个读取
            byte[] bytes = new byte[1024*1024];
            while ((byteCount = inputStream.read(bytes)) != -1){
                outputStream.write(bytes, 0, byteCount);
            }

            inputStream.close();
            outputStream.close();
        } catch (FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
    }
}



第四步 在Controller层创建OssController类

package com.hailan.hailan.controller;

import com.hailan.hailan.util.OssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/oss")
public class OssController {

    @Autowired
    OssUtil ossUtil;  //注入OssUtil

    @PostMapping("/uploadfile")
    public Object fileUpload(@RequestParam("file") MultipartFile file)
    {
        try {
            String url = ossUtil.uploadFile(file); //调用OSS工具类
            Map returnbody = new HashMap<>();
            Map returnMap = new HashMap<>();
            returnMap.put("url", url);
            returnbody.put("data",returnMap);
            returnbody.put("code","200");
            returnbody.put("message","上传成功");
            return returnbody;
        }
        catch (Exception e) {
            Map returnbody = new HashMap<>();
            returnbody.put("data",null);
            returnbody.put("code","400");
            returnbody.put("message","上传失败");
            return  returnbody;
        }
    }

    @PostMapping("/fileDELET")
    public boolean fileDELET(String bucketUrl) {

        boolean b = ossUtil.deleteObject(bucketUrl);

        return b;
    }
}


前端上传

templates下面创建index.html

 


    
    
    
        阿里云oss上传

    


上传文件:

你可能感兴趣的:(springboot,阿里云,upload,阿里云)