1.FileController
package com.atguigu.guli.service.oss.controller.admin;
import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
@Api(tags = "阿里云文件管理")
@CrossOrigin
@RestController
@Slf4j
@RequestMapping("/admin/oss/file")
public class FileController {
@Autowired
private FileService fileService;
/*
文件上传
*/
@PostMapping("upload")
@ApiOperation("文件上传")
public R upload(
@ApiParam(value = "文件",required = true)
@RequestParam("file") MultipartFile file,
@ApiParam(value = "模块",required = true)
@RequestParam("module") String module) {
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
String originalFilename = file.getOriginalFilename();
String url = fileService.upload(inputStream, module, originalFilename);
//返回R对象
return R.ok().message("文件上传成功").data("url",url);
} catch (Exception e) {
log.error(ExceptionUtils.getStackTrace(e));
e.printStackTrace();
throw new GuliException(ResultCodeEnum.FILE_UPLOAD_ERROR);
}
}
@ApiOperation("文件删除")
@DeleteMapping("remove")
public R removeFile(@ApiParam(value = "要删除的文件路径",required = true) @RequestBody String url){
fileService.removeFile(url);
return R.ok().message("文件删除成功");
}
}
2.Service定义接口
package com.atguigu.guli.service.oss.service;
import java.io.InputStream;
public interface FileService {
/*
文件上传至阿里云
*/
String upload(InputStream inputStream,String module,String oFilename);
void removeFile(String url);
}
3.FileServiceImpl
package com.atguigu.guli.service.oss.service.impl;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.atguigu.guli.service.oss.service.FileService;
import com.atguigu.guli.service.oss.util.OssProperties;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.util.UUID;
@Service
public class FileServiceImpl implements FileService {
@Autowired
private OssProperties ossProperties;
@Override
public String upload(InputStream inputStream, String module, String oFilename) {
// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = ossProperties.getEndPoint();
String accessKeyId = ossProperties.getKeyId();
String accessKeySecret = ossProperties.getKeySecret();
String bucketName = ossProperties.getBucketName();
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//判断oos实例是否存在,如果不存在则创建,如果存在则获取
if(!ossClient.doesBucketExist(bucketName)){
//创建bucket
ossClient.createBucket(bucketName);
//设置oss实例的访问权限:公共读
ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
}
//构建日期路径:avatar/2020/06/23/文件名
String folder = new DateTime().toString("yyyy/MM/dd");
//文件名:uuid.扩展名
String fileName = UUID.randomUUID().toString();
String fileExtension = oFilename.substring(oFilename.lastIndexOf("."));
String key = module + "/" + folder+ "/" + fileName + fileExtension;
// 文件上传到阿里云
ossClient.putObject(bucketName, key, inputStream);
// 关闭OSSClient。
ossClient.shutdown();
//返回url地址
return "https://" + bucketName + "." + endpoint + "/" + key;
}
@Override
public void removeFile(String url) {
String endpoint = ossProperties.getEndPoint();
String keyid = ossProperties.getKeyId();
String keysecret = ossProperties.getKeySecret();
String bucketname = ossProperties.getBucketName();
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, keyid, keysecret);
String host = "https://" + bucketname + "." + endpoint + "/";
String objectName = url.substring(host.length());
// 删除文件。
ossClient.deleteObject(bucketname, objectName);
// 关闭OSSClient。
ossClient.shutdown();
}
}
4.form.vue
<el-form-item label="广告图片">
<el-upload
:on-success="handleAvatarSuccess"
:on-error="handleAvatarError"
:on-exceed="handleUploadExceed"
:before-upload="beforeAvatarUpload"
:limit="1"
:file-list="fileList"
action="http://localhost:8120/admin/oss/file/upload?module=ad"
list-type="picture">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
</el-form-item>
// 上传多于一个文件
handleUploadExceed(files, fileList) {
this.$message.warning('想要重新上传图片,请先删除已上传的视频')
},
// 上传校验
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!')
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!')
}
return isJPG && isLt2M
},
// 上传成功回调
handleAvatarSuccess(res, file) {
console.log(res)
if (res.success) {
// console.log(res)
this.ad.imageUrl = res.data.url
// 强制重新渲染
// this.$forceUpdate()
} else {
this.$message.error('上传失败1')
}
},
// 错误处理
handleAvatarError() {
console.log('error')
this.$message.error('上传失败2')
}