阿里云OSSClient上传文件
开发中,经常遇到上传文件的需求,下面我就对阿里云OSS做下总结
Controller层:
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONObject;
import cn.xiaooo.qingyanxiyu.service.UpImgService;
@CrossOrigin
@RestController
public class UpImgController {
public static final Logger logger = LoggerFactory.getLogger(UpImgController.class);
@Autowired
private UpImgService upImgService;
@RequestMapping(value = "/headImgUpload",method = RequestMethod.POST)
public String headImgUpload(HttpServletRequest request,MultipartFile file) {
Map<String, Object> value = new HashMap<String, Object>();
try {
String url = upImgService.updateHead(file);
System.out.println(url);
logger.debug("图片路径:",url);
value.put("data", url);
value.put("code", 0);
value.put("msg", "图片上传成功");
} catch (Exception e) {
value.put("code", 2000);
value.put("msg", "图片上传失败");
}
return JSONObject.toJSONString(value);
}
@RequestMapping(value = "/UploadVideo",method = RequestMethod.POST)
public String UploadVideo(HttpServletRequest request,MultipartFile file) {
Map<String, Object> value = new HashMap<String, Object>();
try {
String url = upImgService.updateVideo(file);
System.out.println(url);
logger.debug("视频路径:",url);
value.put("data", url);
value.put("code", 0);
value.put("msg", "视频上传成功");
} catch (Exception e) {
value.put("code", 2000);
value.put("msg", "视频上传失败");
}
return JSONObject.toJSONString(value);
}
}
Service层:
import org.springframework.web.multipart.MultipartFile;
import cn.xiaooo.qingyanxiyu.util.ImgException;
public interface UpImgService {
String updateHead(MultipartFile file)throws ImgException;
String updateVideo(MultipartFile file)throws ImgException;
}
实现类:
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import cn.xiaooo.qingyanxiyu.util.ImgException;
import cn.xiaooo.qingyanxiyu.util.OSSClientUtil;
@Service
public class UpImgServiceImpl implements UpImgService {
@Override
public String updateHead(MultipartFile file) throws ImgException {
if (file == null || file.getSize() <= 0) {
throw new ImgException("file不能为空");
}
OSSClientUtil ossClient=new OSSClientUtil();
String name = ossClient.uploadImg2Oss(file);
String imgUrl = ossClient.getImgUrl(name);
String[] split = imgUrl.split("\\?");
return split[0];
}
@Override
public String updateVideo(MultipartFile file) throws ImgException {
if (file == null || file.getSize() <= 0) {
throw new ImgException("file不能为空");
}
OSSClientUtil ossClient=new OSSClientUtil();
String name = ossClient.uploadResource(file);
String imgUrl = ossClient.getImgUrl(name);
String[] split = imgUrl.split("\\?");
return split[0];
}
}
涉及到的工具类:
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
public class OSSClientUtil {
// 图保存地址
@Value("${upload.image.path}")
private static String picSavePath;
// 显示url
@Value("${mvn_picContext}")
private static String picShowPath;
public static final Logger logger = LoggerFactory.getLogger(OSSClientUtil.class);
private static String endPoint = "http://oss-cn-shanghai.aliyuncs.com";
private static String bucket = "http://xiaooo.oss-cn-shanghai.aliyuncs.com/";
// endpoint
private String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
// accessKey
private static String accessKeyId = "LTAI0";
private static String accessKeySecret = "V7bcl2V2Pzo2kMUgy";
// 空间
private static String bucketName = "xiaooo";
// 文件存储目录
private String filedir = "whatdoImg/";
private static String remotePath = "laomendong";
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();
}
/**
* 阿里云oss上传图片 @Title:ossUploadPic @Description:TODO @param :@param pic
* 图片流 @param :@param removePath 上传目录 @param :@return @return
* :ResultBody @throws
*/
public static String ossUploadPic(String picture, String picPath) {
if (StringUtils.isEmpty(picture)) {
return null;
}
String path = "";
MultipartFile file = FileUtil.base64ToMultipart(picture);
if (file == null) {
return null;
}
String fileName = FileUtil.getNewFileName("pic", file.getOriginalFilename());
try {
// 创建存储目录
File uploadPath = FileUtil.createFolder(picSavePath + "/" + picPath);
FileUtil.uploadImage(fileName, uploadPath, file.getInputStream());
// 生成OSSClient,您可以指定一些参数,详见“SDK手册 > Java-SDK > 初始化”,
// 链接地址是:https://help.aliyun.com/document_detail/oss/sdk/java-sdk/init.html?spm=5176.docoss/sdk/java-sdk/get-start
OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
if (!ossClient.doesBucketExist(bucketName)) {
ossClient.createBucket(bucketName);
}
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(file.getInputStream().available());
objectMetadata.setContentEncoding("utf-8");
objectMetadata.setCacheControl("no-cache");
objectMetadata.setHeader("Pragma", "no-cache");
objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
objectMetadata.setContentDisposition("inline;filename=" + fileName);
path = remotePath + "/" + picPath + "/" + fileName;
ossClient.putObject(bucketName, path, file.getInputStream(), objectMetadata);
ossClient.shutdown();
file.getInputStream().close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
String showPath = bucket + path;
return showPath;
}
public String uploadImg2Oss(MultipartFile file) throws ImgException {
if (file.getSize() > 10 * 1024 * 1024) {
throw new ImgException("上传图片大小不能超过10M!");
}
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) {
throw new ImgException("图片上传失败");
}
}
/**
* 上传视频
* @param file
* @return
* @throws ResourceException
*/
public String uploadResource(MultipartFile file) throws ImgException {
if (file.getSize() > 20 * 1024 * 1024) {
throw new ImgException("上传视频大小不能超过20M!");
}
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) {
throw new ImgException("视频上传失败");
}
}
/**
* 获得图片路径
* @param fileUrl
* @return
*/
public String getImgUrl(String fileUrl) {
System.out.println(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) {
logger.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")) {
return "video/mp4";
}
if (filenameExtension.equalsIgnoreCase(".avi")) {
return "video/avi";
}
if (filenameExtension.equalsIgnoreCase(".qsv")) {
return "video/qsv";
}
return "image/jpeg";
}
/** * 获得url链接
* @param key
* @return
*/
public String getUrl(String key) {
// 设置URL过期时间为10年 3600l* 1000*24*365*10
Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
// 生成URL
URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
if (url != null) {
return url.toString();
}
return null;
}
}
视频格式可以自己进行修改
原文作者:權先森和香香
原文地址: https://blog.csdn.net/weixin_41146000/article/details/103768380
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/weixin_41146000/article/details/103768380
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
相关文章