springboot+vue+elementui upload組件批量自動/手動上傳圖片到阿里雲OSS
一、vue upload上傳組件
1、自動上傳
介紹:當在瀏覽器打開圖片選擇彈出框,選中圖片後點擊確定按鈕就會立刻上傳。
代碼:
<!-- html代碼 -->
<el-upload
class="upload-demo"
accept="image/png,image/jpg,image/jpeg"
:show-file-list="false"
multiple
action="#"
:http-request="imageUpload"
>
<el-button slot="trigger" size="small" class="uploadImgBtn" >選取文件</el-button>
<span slot="tip">(只能上傳jpg/png格式圖片,且圖片大小不超過500KB)</span>
</el-upload>
<!-- js代碼 -->
imageUpload:function(param) {
let that = this;
// 先判斷圖片大小
const _file = param.file;
const _fileSize = _file.size < 1024 * 500;
if (!_fileSize) {
that.$message.warning("請上傳500KB以下的圖片文件");
return false;
}
// 參數
let params = new FormData();
params.append('questionImages', _file);
that.$axios({
url: api.uploadQusImages,//後臺接口
method: "post",
data: params,
headers: {
"Content-Type": "multipart/form-data"
}
})
.then(function(res) {
if (res.data.code == "ok") {
that.$message.success('上傳成功');
}else{
that.$message.error('上傳失敗');
}
})
.catch(function(err) {
that.$message.error('系統內部異常');
});
},
解釋:
accept:自動過濾不符合圖片,
multiple 支持批量上傳
action="#" 上傳地址,可以不用但是一定要寫
:http-request="imageUpload" 覆蓋默認的上傳行爲,可以自定義上傳的實現
2、手動上傳
介紹:選擇圖片,展示待上傳圖片列表,點擊上傳按鈕,上傳至圖片服務器
代碼:
<!-- html代碼 -->
<el-upload
class="upload-demo"
accept="image/png,image/jpg,image/jpeg"
ref="upload"
:file-list="fileLists"
multiple
action="#"
:on-change="handlePreview"
:on-remove="handleRemove"
list-type="text"
:limit="9"
:on-exceed="fileExceed"
:auto-upload="false">
<el-button slot="trigger" size="small" type="primary">選取文件</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上傳到服務器</el-button>
<div slot="tip" class="el-upload__tip">只能上傳jpg/png格式圖片,且圖片大小不超過2MB</div>
</el-upload>
<!-- js代碼 -->
vue data 中定義fileLists[],
submitUpload() {
let that = this;
let params = new FormData();
// 注意此處對文件數組進行了參數循環添加
if(that.fileLists.length>0){
that.fileLists.forEach(function (file) {
params.append('questionImages', file.raw);
})
}else{
that.$message.warning("當前沒有合適圖片可以上傳");
}
that.$axios({
url: api.uploadQusImages,
method: "post",
data: params,
headers: {
"Content-Type": "multipart/form-data"
}
})
.then(function(res) {
if (res.data.result == "ok") {
that.$message.success('上傳成功!');
}
})
.catch(function(err) {
that.$message.error('網絡請求異常!');
});
},
handleRemove(file, fileList) {
this.fileLists = fileList;
},
handlePreview(file, fileList) {
let that = this;
if (file.raw.type != 'image/jpg'&& file.raw.type != 'image/png') {
that.$message.error('圖片只能是jpg/png格式!');
return;
}
if (file.raw.size > 1024 * 1024 * 2) {
that.$message.error('上傳文件大小不能超過 2MB!');
return;
}
that.fileLists = fileList;
},
fileExceed:function(files, fileList){
this.$message.warning(`當前限制選擇 9 個文件,本次選擇了 ${files.length} 個文件,共選擇了 ${files.length + fileList.length} 個文件`)
},
清空上傳文件:
that.fileLists = [];
this.$refs['upload'].clearFiles();
二、springboot後臺
1、controller層接口
@PostMapping(value="/uploadQusImages",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Map<String,Object> uploadQusImages(@RequestParam("questionImages") MultipartFile[] questionImages){
if(questionImages != null && questionImages.length > 0){
return questionManage.uploadQusImages(questionImages);
}else{
log.info("questionImages is null");
Map<String,Object> map = new HashMap<String,Object>();
map.put("code", Constants.RESULT_NULL);
return map;
}
}
2、service層方法
注意事項:阿里雲OSS上傳其實不支持圖片批量上傳,所以將圖片文件循環,轉化成文件流,在循環中進行單圖片上傳操作。
public Map<String,Object> uploadQusImages(MultipartFile[] questionImages) {
Map<String,Object> map = new HashMap<String,Object>();
List<ImgDetail> listImgDetail = new ArrayList<ImgDetail>();
try {
for(MultipartFile file:questionImages){
String fileName = file.getOriginalFilename();
InputStream fileStrem = file.getInputStream();
String fileUrl = AliyunOSSUtil.uploadStemImage(fileStrem,fileName);
if(!Constants.RESULT_ERROR.equals(fileUrl)){
listImgDetail.add(imgDetail);
}
}
// 將上傳成功圖片全部添加到數據庫中
Result result = imgGroupManage.insertImgDetail(listImgDetail);
// 圖片插入結果
if((Constants.RESULT_OK).equals(result.getResult())){
map.put("code",Constants.RESULT_OK);
map.put("data",listImgDetail);
}else{
map.put("code",Constants.RESULT_ERROR);
}
} catch (IOException e) {
map.put("code", Constants.RESULT_ERROR);
log.error(e.getMessage());
}
return map;
}
3、圖片上傳工具類
public static String uploadStemImage(InputStream inputStreamFile,String fileName){
// 新建一個OSS對象
OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
try {
//bucket容器不存在,就創建
if(! ossClient.doesBucketExist(bucketname)){
ossClient.createBucket(bucketname);
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketname);
createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
ossClient.createBucket(createBucketRequest);
}
//創建文件路徑,DateTimeUtil時間工具類
String fileUrl = DateTimeUtil.getNowDateString2() + "/" + UUID.randomUUID().toString().replace("-","")+"-"+fileName;
//上傳文件
PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketname, fileUrl, inputStreamFile));
log.info("========OSS上傳文件結果:"+result);
//設置權限 這裏是公開讀
ossClient.setBucketAcl(bucketname,CannedAccessControlList.PublicRead);
if(null != result){
log.info("==========OSS文件上傳成功,文件名:"+fileUrl);
// 返回文件url訪問路徑
return filehost+"/"+fileUrl;
}else{
log.info("==========OSS文件上傳失敗==========");
return Constants.RESULT_ERROR;
}
}catch (OSSException oe){
log.error(oe.getMessage());
return Constants.RESULT_ERROR;
}catch (ClientException ce){
log.error(ce.getMessage());
return Constants.RESULT_ERROR;
}finally {
//關閉 ossClient
ossClient.shutdown();
}
}
4、阿里雲OSS上傳pom文件依賴
<!--aliyunOSS-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.4.0</version>
</dependency>
<!-- file/image upload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
總結:關於阿里雲上傳配置信息請查看該博客:https://blog.csdn.net/CoderYin/article/details/90173118
// 文件上傳大小後臺限制
spring:
servlet:
multipart:
max-file-size: 500k
max-request-size : 200Mb