OSS服务器上传

OSSClientUtil工具类

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.Random;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
 
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
 
/**
 * 阿里云 OSS工具类
 */
public class OSSClientUtil {
  Log log = LogFactory.getLog(OSSClientUtil.class);
  // endpoint
  private String endpoint = "oss-cn-beijing.aliyuncs.com";
  // accessKeyId
  private String accessKeyId = "LTAILzcfE4R6C3AS";
  // accessKeySecret
  private String accessKeySecret = "vcajEXmPjbWsp0ch0t4yIXiS5EASsO";
  // bucket
  private String bucketName = "demo";
  // 文件存储目录
  private String filedir = "201802/";
 
  private OSSClient ossClient;
 
  public OSSClientUtil() {
    ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  }
 
  /**
   * 初始化
   */
  public void init() {
    ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  }
 
  /**
   * 销毁
   */
  public void destory() {
    ossClient.shutdown();
  }
 
  /**
   * 上传
   *
   * @param url
   */
  public void uploadOss(String url) {
    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) {
      
    }
  }
 
 
  public String uploadOss(MultipartFile file) {
    String originalFilename = file.getOriginalFilename();
    String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
    Random random = new Random();
    String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
    try {
      InputStream inputStream = file.getInputStream();
      this.uploadFile2OSS(inputStream, name);
      return name;
    } catch (Exception e) {
      return null;
    }
  }
 
  /**
   * 获得路径
   *
   * @param fileUrl
   * @return
   */
  public String getVideoUrl(String fileUrl) {
    if (!StringUtils.isEmpty(fileUrl)) {
      String[] split = fileUrl.split("/");
      return this.getUrl(this.filedir + split[split.length - 1]);
    }
    return null;
  }
 
  /**
   * 上传到OSS服务器  如果同名文件会覆盖服务器上的
   *
   * @param instream 文件流
   * @param fileName 文件名称 包括后缀名
   * @return 出错返回"" ,唯一MD5数字签名
   */
  public String uploadFile2OSS(InputStream instream, String fileName) {
    String ret = "";
    try {
      //创建上传Object的Metadata 
      ObjectMetadata objectMetadata = new ObjectMetadata();
      objectMetadata.setContentLength(instream.available());
      objectMetadata.setCacheControl("no-cache");
      objectMetadata.setHeader("Pragma", "no-cache");
      objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
      objectMetadata.setContentDisposition("inline;filename=" + fileName);
      //上传文件
      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;
  }
 
  /**
   * Description: 判断OSS服务文件上传时文件的contentType
   *
   * @param FilenameExtension 文件后缀
   * @return String
   */
  public 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";
    }
    if (FilenameExtension.equalsIgnoreCase("mp4") || 
    FilenameExtension.equalsIgnoreCase("MP4")) {
return "application/octet-stream";
}
if (FilenameExtension.equalsIgnoreCase("mp3") || 
FilenameExtension.equalsIgnoreCase("MP3")) {
return "audio/mpeg";
}
    return "image/jpeg";
  }
 
  /**
   * 获得url链接
   *
   * @param key
   * @return
   */
  public String getUrl(String key) {
    // 设置URL过期时间为10年  3600l* 1000*24*365*10
    Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
    // 生成URL
    URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
    if (url != null) {
      return url.toString();
    }
    return null;
  }

}


Oss上传Controller

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.education_online.util.OSSClientUtil;

@Controller
public class OssController {

OSSClientUtil ossClient = new OSSClientUtil();

@RequestMapping(value = "ossuploaad", method = RequestMethod.POST)
public @ResponseBody String headImgUpload(HttpServletRequest request,MultipartFile file) {

    String name = ossClient.uploadOss(file);

    String imgUrl = ossClient.getVideoUrl(name);
    return imgUrl;//返回文件存储地址
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值