前端
/* eslint-disable */
<template>
<div>
<el-upload
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove"
:before-upload="onBeforeUpload"
:on-exceed="handleExceed"
:on-success="handSuccess"
:limit="limit"
:file-list="imageUrl"
:headers="headers"
multiple
accept="image/jpeg,image/gif,image/png"
list-type="picture-card"
:action="imagesUploadApi"
>
<i class="el-icon-plus" />
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img
:src="dialogImageUrl"
width="100%"
alt=""
>
</el-dialog>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
export default {
props: {
limit: {
type: Number,
required: true
}
},
data() {
return {
dialogImageUrl: '',
dialogVisible: false,
imageUrl: [],
image: { url: '' },
urls: '',
headers: {
'Authorization': getToken()
}
}
},
computed: {
...mapGetters([
'imagesUploadApi'
])
},
mounted() {},
methods: {
handleRemove(file, fileList) {
const imageTemporaryArr = []
for (var item of this.imageUrl) {
if (item.url !== file.url) {
imageTemporaryArr.push(item)
}
}
this.imageUrl = imageTemporaryArr
},
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url
this.dialogVisible = true
},
handleExceed() {
this.$message.error('超出上传限制!')
},
handSuccess(response, file, fileList) {
this.image = {}
this.image.url = response.url
this.imageUrl.push(this.image)
},
onBeforeUpload(file) {
const isIMAGE = file.type === 'image/jpeg' || 'image/gif' || 'image/png'
const isLt1M = file.size / 1024 / 1024 < 1
if (!isIMAGE) {
this.$message.error('上传文件只能是图片格式!')
}
if (!isLt1M) {
this.$message.error('上传文件大小不能超过 1MB!')
}
return isIMAGE && isLt1M
},
setValue(r) {
this.imageUrl = r
},
getValue() {
this.urls = ''
for (var item of this.imageUrl) {
this.urls += item.url + ','
}
return this.urls.substring(0, this.urls.length - 1)
}
}
}
</script>
<style scoped>
.editor-content {
padding-left: 5px;
}
</style>
后端
@Slf4j
@RequiredArgsConstructor
@Service(value = "aliPictureService")
public class AliPictureServiceImpl {
private final PictureRepository pictureRepository;
@Transactional(rollbackFor = Throwable.class)
public Picture upload(MultipartFile multipartFile, String username) {
Picture picture = new Picture();
String url = UploadOss.uploadFile(multipartFile);
picture.setUrl(url);
return picture;
}
}
public class UploadOss {
// Endpoint以杭州为例,其它Region请按实际情况填写。
private static String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运 维,请登录RAM控制台创建RAM账号。
private static String accessKeyId = "<yourAccessKeyId>";
private static String accessKeySecret = "<yourAccessKeySecret>";
private static String bucketName = "<yourBucketName>";
/**
* 阿里云图片地址
**/
public final static String GET_ALI_BUCK_URL = "http://<yourBucketName>.oss-cn-beijing.aliyuncs.com";
public static String fileName = "<picturesName>/";//文件夹名称
/**
* 上传文件,返回访问链接
* <p>Description: </p>
*
* @param imageFile
* @return
* @author: luoshun
* @version: v1.0 2016年10月24日
*/
public static String uploadFile(MultipartFile imageFile) {
String fileNames = new Date().getTime() + "." +FileUtil.getExtensionName(imageFile.getOriginalFilename());
try {
InputStream stream = imageFile.getInputStream();
Long size = imageFile.getSize();
fileNames = UploadOss.uploadFile(fileNames, stream, size);
return GET_ALI_BUCK_URL + "/" + fileName + fileNames;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 【上传到阿里云】(这里用一句话描述这个方法的作用)
*
* @param key
* @param stream
* @param size
* @return
* @throws Exception
*/
public static String uploadFile(String key, InputStream stream, long size) throws Exception {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String d = formatter.format(new Date());
String first = d.substring(0, 7).replace("-", "");
String sec = d.substring(8, 10);
key = first + "/" + sec + "/" + key;
OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
ObjectMetadata meta = new ObjectMetadata();
meta.setContentLength(size);
client.putObject(bucketName, fileName + key, stream, meta);
return key;
}
}
https://blog.youkuaiyun.com/Platinum_stars/article/details/107060331