前言
- Java开发中将本地文件上传至阿里云服务器上
代码实现
1.Controller接口实现
@RestController
@RequestMapping("/help")
public class UploadAliyunController {
private final static Logger LOG = LoggerFactory.getLogger(UploadAliyunController.class);
/**
* @return
* @function 视频上传
*/
@PostMapping("uploadVideo")
public Map uploadVideo(@RequestHeader(value = "lid") String lid,@RequestParam(value = "file") MultipartFile file) {
if (StringUtils.isBlank(file.getOriginalFilename())) {
//return R.error(500, "内容为空");
throw new RRException("请上传视频", 10001);
}
String fileName = file.getOriginalFilename();
fileName = fileName.substring(fileName.lastIndexOf(".") + 1);
//&& !"webm".equals(fileName) && !"ogg".equals(fileName)
if (!"mp4".equals(fileName) ) {
throw new RRException("上传视频格式不正确!", 10003);
}
if (file.getSize() >= 1073741824) {
throw new RRException("文件不要超过1G", 10005);
}
String videoUrl = OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_VIDEO);
if (StringUtils.isBlank(videoUrl)){
Map map = new HashMap();
map.put("code", 1);//0表示成功,1失败
map.put("msg", "上传失败");//提示消息
map.put("coverURL", videoUrl);//图片url
Map<String, Object> Imgmap = new HashMap<>();
Imgmap.put("src", videoUrl);//图片url
Imgmap.put("title", file.getOriginalFilename());//图片名称
map.put("data", Imgmap);
return map;
}
Map map = new HashMap();
map.put("code", 0);//0表示成功,1失败
map.put("msg", "上传成功");//提示消息
//map.put("imgUrl", imgUrl);//图片url
map.put("coverURL", videoUrl);//图片url
Map<String, Object> Imgmap = new HashMap<>();
Imgmap.put("src", videoUrl);//图片url
Imgmap.put("title", file.getOriginalFilename());//图片名称
map.put("data", Imgmap);
return map;
}
/**
* @param file
* @return
* @function 图片上传
*/
@PostMapping("uploadImage")
public Map uploadImages(@RequestHeader(value = "lid") String lid,@RequestParam(value = "file") MultipartFile file) {
if (StringUtils.isBlank(file.getOriginalFilename())) {
throw new RRException("请选择上传的图片", 10001);
}
String fileName = file.getOriginalFilename();
fileName = fileName.substring(fileName.lastIndexOf(".") + 1);
if (!"png".equals(fileName) && !"jpg".equals(fileName) && !"jpeg".equals(fileName) && !"gif".equals(fileName)) {
throw new RRException("上传图片的格式不正确", 10002);
}
if (file.getSize() >= 5242880) {
throw new RRException("图片大小超过5M", 10005);
}
String imgUrl = OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_IMAGES);
if (StringUtils.isBlank(imgUrl)){
Map map = new HashMap();
map.put("code", 302);//0表示成功,1失败
map.put("msg", "上传失败");//提示消息
Map<String, Object> Imgmap = new HashMap<>();
Imgmap.put("src", imgUrl);//图片url
Imgmap.put("title", file.getOriginalFilename());//图片名称
map.put("data", Imgmap);
return map;
}
Map map = new HashMap();
map.put("code", 200);
map.put("msg", "上传成功");//提示消息
Map<String, Object> Imgmap = new HashMap<>();
Imgmap.put("src", imgUrl);//图片url
Imgmap.put("title", file.getOriginalFilename());//图片名称
map.put("data", Imgmap);
return map;
}
/**
* @param file
* @return
* @function 文件上传
*/
@PostMapping("uploadFile")
public Map uploadFile(@RequestHeader(value = "lid") String lid,@RequestParam(value = "file") MultipartFile file) {
if (StringUtils.isBlank(file.getOriginalFilename())) {
throw new RRException("请选择上传文件", 10001);
}
String fileName = file.getOriginalFilename();
fileName = fileName.substring(fileName.lastIndexOf(".") + 1);
if (!"jpg".equals(fileName) && !"png".equals(fileName) && !"jpeg".equals(fileName) && !"gif".equals(fileName) && !"doc".equals(fileName) && !"docx".equals(fileName) && !"pdf".equals(fileName)) {
throw new RRException("文件格式不正确", 10002);
}
if (file.getSize() >= 5242880) {
throw new RRException("文件大小超过5M", 10005);
}
String fileUrl = OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_FILE);
Map<String, Object> Imgmap = new HashMap<>();
Imgmap.put("url", fileUrl);//图片url
Imgmap.put("fileName", file.getOriginalFilename());//图片名称
if (StringUtils.isBlank(fileUrl)){
return R.error("上传失败").put("results",Imgmap);
}
return R.ok().put("results",Imgmap);
}
@GetMapping("delUpload")
@ApiOperation("删除上传文件")
public R delUpload(@RequestHeader(value = "lid") String lid,@RequestParam(value = "url") String fileName) {
if (StringUtils.isBlank(fileName)) {
throw new RRException("请选择删除文件", 10001);
}
Boolean result = OssUtil.deleteOne(fileName);
if (result) {
return R.ok("删除成功");
} else {
throw new RRException("删除失败,文件不存在");
}
}
}
2.yml配置
3.阿里云上传相关工具类
public class OssUtil {
private static final String PROPETIES_PATH = "application.yml";
private static final Properties PROP = PropertiesUtils.getProperties(PROPETIES_PATH);
private final static Logger LOG = LoggerFactory.getLogger(OssUtil.class);
/**
* 域名
*/
private final static String OSS_END_POINT = PROP.getProperty("ossendpoint");
/**
* 账号
*/
private final static String OSS_ACCESS_KEY_ID = PROP.getProperty("ossaccesskeyid");
/**
* 密匙
*/
private final static String OSS_ACCESS_KEY_SECRET = PROP.getProperty("ossaccesskeysecet");
/**
* 存储空间
*/
private final static String OSS_BUCKET_NAME = PROP.getProperty("ossbucketname");
/**
* URL有效期
*/
private final static Date OSS_URL_EXPIRATION = DateUtils.addDays(new Date(), 365 * 10);
private volatile static OSS instance = null;
private OssUtil() {
}
/**
* Oss 实例化
*
* @return
*/
private static OSS getOssClient() {
if (instance == null) {
synchronized (OssUtil.class) {
if (instance == null) {
instance = new OSSClientBuilder().build(OSS_END_POINT, OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET);
}
}
}
return instance;
}
private static void colseOssClient() {
if (OssUtil.getOssClient() != null) {
OssUtil.getOssClient().shutdown();
}
}
/**
* 文件路径的枚举
*/
public enum FileDirType {
ARTICLE_IMAGES("help_images"), ARTICLE_VIDEO("help_video"), ARTICLE_FILE("help_file"), CAROUSEL("carousel"), MENU("menu");
private String dir;
FileDirType(String dir) {
this.dir = dir;
}
@JsonValue
public String getDir() {
return dir;
}
}
/**
* 当Bucket 不存在时候创建Bucket
*/
private static void createBuchet() {
try {
if (!OssUtil.getOssClient().doesBucketExist(OSS_BUCKET_NAME)) {
OssUtil.getOssClient().createBucket(OSS_BUCKET_NAME);
}
} catch (Exception e) {
LOG.warn("创建BUCHET失败:", e);
throw new ClientException("创建Bucket失败,请核对Bucket名称(规则:只能包含小写字母、数字和短横线,必须以小写字母和数字开头和结尾,长度在3-63之间)");
}
}
/**
* 文件上传的文件后缀
*
* @param filenameExtension
* @return
*/
private static String getContentType(String filenameExtension) {
String type = null;
switch (filenameExtension) {
case "jpeg":
case "jpg":
type = "image/jpeg";
break;
case "png":
type = "image/png";
break;
case "gif":
type = "image/gif";
break;
case "pdf":
type = "application/pdf";
break;
case "doc":
case "docx":
type = "application/msword";
break;
case "mp4":
type = "video/mpeg4";
break;
default:
type = filenameExtension;
break;
}
return type;
}
/**
* 上传OSS服务器 如果同名文件会覆盖服务器上的
* jdk1.7新特性的书写方式:try-with-resource,可以实现自动关流操作
* @param file
* @param fileDirType
* @return
*/
private static String uploadFile(MultipartFile file, FileDirType fileDirType) {
String fileName = String.format("%s.%s", UUID.randomUUID().toString(), FilenameUtils.getExtension(file.getOriginalFilename()));
try (InputStream inputStream = file.getInputStream()) {
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(inputStream.available());
objectMetadata.setCacheControl("no-cache");
objectMetadata.setHeader("Pragma", "no-cache");
objectMetadata.setContentType(getContentType(FilenameUtils.getExtension("." + file.getOriginalFilename())));
objectMetadata.setContentDisposition("inline;filename=" + fileName);
//校验MD5
objectMetadata.setContentMD5(BinaryUtil.toBase64String(BinaryUtil.calculateMd5(file.getBytes())));
PutObjectResult putObjectResult = OssUtil.getOssClient().putObject(OSS_BUCKET_NAME, fileDirType.getDir() + "/" + fileName, inputStream, objectMetadata);
LOG.info("成功之putObjectResult:" + putObjectResult);
return fileDirType.getDir() + "/" + fileName;
} catch (OSSException oe) {
LOG.warn("上传文件之OSSException异常:", oe);
LOG.warn("Error Message: " + oe.getErrorCode());
LOG.warn("Error Code: " + oe.getErrorCode());
LOG.warn("Request ID: " + oe.getRequestId());
LOG.warn("Host ID: " + oe.getHostId());
return null;
} catch (ClientException ce) {
LOG.warn("上传文件之ClientException异常:", ce);
LOG.warn("Error Message: " + ce.getMessage());
return null;
} catch (IOException e) {
LOG.warn("上传文件之IOException异常:", e);
LOG.warn("Error Message: " + e.getMessage());
return null;
}
}
/**
* 获取文件路径
*
* @param fileUrl
* @param fileDirType
* @return
*/
private static String getFileUrl(String fileUrl, FileDirType fileDirType) {
if (StringUtils.isEmpty(fileUrl)) {
throw new RuntimeException("文件地址为空!");
}
String[] split = fileUrl.split("/");
URL url = OssUtil.getOssClient().generatePresignedUrl(OSS_BUCKET_NAME, fileDirType.getDir() + "/" + split[split.length - 1], OSS_URL_EXPIRATION);
if (url == null) {
throw new RuntimeException("获取OSS文件URL失败!");
}
return url.toString();
}
/**
* 文件上传 去掉URL中的?后的时间戳
* 设置成公共的独写,把问号后面的东西给截取掉
* @param file
* @param fileDirType
* @return
*/
public static String upload(MultipartFile file, FileDirType fileDirType) {
OssUtil.createBuchet();
String fileName = OssUtil.uploadFile(file, fileDirType);
if (StringUtils.isBlank(fileName)) {
return null;
}
String fileOssUrl = OssUtil.getFileUrl(fileName, fileDirType);
int firstChar = fileOssUrl.indexOf("?");
if (firstChar > 0) {
fileOssUrl = fileOssUrl.substring(0, firstChar);
}
return fileOssUrl;
}
/**
* 获取路径地址
*
* @param fileName
* @return
*/
public static String getPathUrl(String fileName) {
return fileName.substring(fileName.indexOf(OSS_END_POINT) + OSS_END_POINT.length() + 1);
}
/**
* 文件删除,删除集合
*
* @param keys
*/
public static void delete(List<String> keys) {
List<String> newKeys = keys.stream().map((item) -> {
return OssUtil.getPathUrl(item);
}).collect(Collectors.toList());
try {
DeleteObjectsResult deleteObjectsResult = OssUtil.getOssClient().deleteObjects(new DeleteObjectsRequest(OSS_BUCKET_NAME).withKeys(newKeys));
List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
System.out.println(deletedObjects);
} catch (OSSException oe) {
LOG.warn("批量删除之OSSException异常:", oe);
LOG.warn("Error Message: " + oe.getErrorCode());
LOG.warn("Error Code: " + oe.getErrorCode());
LOG.warn("Request ID: " + oe.getRequestId());
LOG.warn("Host ID: " + oe.getHostId());
} catch (ClientException ce) {
LOG.warn("批量删除之ClientException异常:", ce);
LOG.warn("Error Message: " + ce.getMessage());
}
}
/**
* 获取文件名字
*
* @return
*/
public static String getFileName(String filename) {
String file = "";
if (filename.contains(FileDirType.ARTICLE_IMAGES.getDir())) {
file = FileDirType.ARTICLE_IMAGES.getDir();
} else if (filename.contains(FileDirType.ARTICLE_VIDEO.getDir())) {
file = FileDirType.ARTICLE_VIDEO.getDir();
} else {
file = FileDirType.ARTICLE_FILE.getDir();
}
int firstChar = filename.indexOf("?");
if (firstChar > 0) {
filename = filename.substring(0, firstChar);
}
filename = file + filename.substring(filename.lastIndexOf("/"));
return filename;
}
public static boolean deleteOne(String filename) {
filename = OssUtil.getFileName(filename);
boolean found = OssUtil.getOssClient().doesObjectExist(OSS_BUCKET_NAME, filename);
if (found) {
// 删除文件。如需删除文件夹,请将ObjectName设置为对应的文件夹名称。如果文件夹非空,则需要将文件夹下的所有object删除后才能删除该文件夹。
OssUtil.getOssClient().deleteObject(OSS_BUCKET_NAME, filename);
return true;
}
return false;
}
}
/**
* 自定义异常类
*
* *
*/
public class RRException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String msg;
private int code = 500;
public RRException(String msg) {
super(msg);
this.msg = msg;
}
public RRException(String msg, Throwable e) {
super(msg, e);
this.msg = msg;
}
public RRException(String msg, int code) {
super(msg);
this.msg = msg;
this.code = code;
}
public RRException(String msg, int code, Throwable e) {
super(msg, e);
this.msg = msg;
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
/**
* @author jwang properties文件读写工具类
*
*/
public abstract class PropertiesUtils {
private final static Logger LOG = LoggerFactory.getLogger(PropertiesUtils.class);
public static Properties getProperties(String path) {
Properties prop = new Properties();
loadProp(prop, path);
return prop;
}
private static void loadProp(Properties p, String conf) {
InputStream is = getInputStream(conf);
if (null != is) {
try {
p.load(is);
} catch (IOException e) {
LOG.info("file not found!");
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
LOG.info("stream close fail!");
}
}
}
}
}
// 获取输入流
private static InputStream getInputStream(String conf) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream is = null;
if (null != classLoader) {
is = classLoader.getResourceAsStream(conf);
}
return is;
}
// 获取输出流
private static OutputStream getOutPutStream(String conf) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
OutputStream out = null;
if (null != classLoader) {
String filePath = classLoader.getResource(conf).getFile();
try {
out = new FileOutputStream(filePath);
} catch (FileNotFoundException e) {
LOG.info("file not found!!!");
}
}
return out;
}
// 读取key=value
public static String getValue(Properties p, String key) {
String value = p.getProperty(key);
return value == null ? "" : value;
}
// 设置key=value
public static void setValue(String conf, String key, String value) {
Properties p = getProperties(conf);
OutputStream out = getOutPutStream(conf);
p.setProperty(key, value);
try {
p.store(out, "set:" + key + "=" + value);
} catch (IOException e) {
LOG.info("set properties fail!!!");
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
LOG.info("stream close fail!");
}
}
}
}
}