最終效果圖
文章來源地址http://www.zghlxwxcb.cn/news/detail-851185.html
uniapp 的源碼
UpLoadFile.vue
<template>
<!-- 上傳start -->
<view style="display: flex; flex-wrap: wrap;">
<view class="update-file">
<!--圖片-->
<view v-for="(item,index) in imageList" :key="index">
<view class="upload-box">
<image class="preview-file" :src="item" @tap="previewImage(item)"></image>
<view class="remove-icon" @tap="delect(index)">
<u-icon name="trash"></u-icon>
<!-- <image src="../../static/images/del.png" class="del-icon" mode=""></image> -->
</view>
</view>
</view>
<!--視頻-->
<view v-for="(item1, index1) in srcVideo" :key="index1">
<view class="upload-box">
<video class="preview-file" :src="item1"></video>
<view class="remove-icon" @tap="delectVideo(index1)">
<u-icon name="trash"></u-icon>
<!-- <image src="../../static/images/del.png" class="del-icon" mode=""></image> -->
</view>
</view>
</view>
<!--按鈕-->
<view v-if="VideoOfImagesShow" @tap="chooseVideoImage" class="upload-btn">
<!-- <image src="../../static/images/jia.png" style="width:30rpx;height:30rpx;" mode=""></image> -->
<view class="btn-text">上傳</view>
</view>
</view>
</view>
<!-- 上傳 end -->
</template>
<script>
import {
deleteFileApi
} from '../../api/file/deleteOssFile';
var sourceType = [
['camera'],
['album'],
['camera', 'album']
];
export default {
data() {
return {
hostUrl: "http://192.168.163.30:9999/api/file/upload",
// 上傳圖片視頻
VideoOfImagesShow: true, // 頁面圖片或視頻數(shù)量超出后,拍照按鈕隱藏
imageList: [], //存放圖片的地址
srcVideo: [], //視頻存放的地址
sourceType: ['拍攝', '相冊', '拍攝或相冊'],
sourceTypeIndex: 2,
cameraList: [{
value: 'back',
name: '后置攝像頭',
checked: 'true'
}, {
value: 'front',
name: '前置攝像頭'
}],
cameraIndex: 0, //上傳視頻時的數(shù)量
//上傳圖片和視頻
uploadFiles: [],
}
},
onUnload() {
// 上傳
this.imageList = [];
this.sourceTypeIndex = 2;
this.sourceType = ['拍攝', '相冊', '拍攝或相冊'];
},
methods: {
//點擊上傳圖片或視頻
chooseVideoImage() {
uni.showActionSheet({
title: '選擇上傳類型',
itemList: ['圖片', '視頻'],
success: res => {
console.log(res);
if (res.tapIndex == 0) {
this.chooseImages();
} else {
this.chooseVideo();
}
}
});
},
//上傳圖片
chooseImages() {
uni.chooseImage({
count: 9, //默認是9張
sizeType: ['original', 'compressed'], //可以指定是原圖還是壓縮圖,默認二者都有
sourceType: ['album', 'camera'], //從相冊選擇
success: res => {
console.log(res, 'ddddsss')
let imgFile = res.tempFilePaths;
imgFile.forEach(item => {
uni.uploadFile({
url: this.hostUrl, //僅為示例,非真實的接口地址
method: "POST",
header: {
token: uni.getStorageSync('localtoken')
},
filePath: item,
name: 'file',
success: (result) => {
let res = JSON.parse(result.data)
console.log('打印res:', res)
if (res.code == 200) {
this.imageList = this.imageList.concat(res.data);
console.log(this.imageList, '上傳圖片成功')
if (this.imageList.length >= 9) {
this.VideoOfImagesShow = false;
} else {
this.VideoOfImagesShow = true;
}
}
uni.showToast({
title: res.msg,
icon: 'none'
})
}
})
})
}
})
},
//上傳視頻
chooseVideo(index) {
uni.chooseVideo({
maxDuration: 120, //拍攝視頻最長拍攝時間,單位秒。最長支持 60 秒
count: 9,
camera: this.cameraList[this.cameraIndex].value, //'front'、'back',默認'back'
sourceType: sourceType[this.sourceTypeIndex],
success: res => {
let videoFile = res.tempFilePath;
uni.showLoading({
title: '上傳中...'
});
uni.uploadFile({
url: this.hostUrl, //上傳文件接口地址
method: "POST",
header: {
token: uni.getStorageSync('localtoken')
},
filePath: videoFile,
name: 'file',
success: (result) => {
uni.hideLoading();
let res = JSON.parse(result.data)
if (res.code == 200) {
console.log(res);
this.srcVideo = this.srcVideo.concat(res.data);
if (this.srcVideo.length == 9) {
this.VideoOfImagesShow = false;
}
}
uni.showToast({
title: res.msg,
icon: 'none'
})
},
fail: (error) => {
uni.hideLoading();
uni.showToast({
title: error,
icon: 'none'
})
}
})
},
fail: (error) => {
uni.hideLoading();
uni.showToast({
title: error,
icon: 'none'
})
}
})
},
//預覽圖片
previewImage: function(item) {
console.log('預覽圖片', item)
uni.previewImage({
current: item,
urls: this.imageList
});
},
// 刪除圖片
delect(index) {
uni.showModal({
title: '提示',
content: '是否要刪除該圖片',
success: res => {
if (res.confirm) {
deleteFileApi(this.imageList[index].split("/")[3]);
this.imageList.splice(index, 1);
}
if (this.imageList.length == 4) {
this.VideoOfImagesShow = false;
} else {
this.VideoOfImagesShow = true;
}
}
});
},
// 刪除視頻
delectVideo(index) {
uni.showModal({
title: '提示',
content: '是否要刪除此視頻',
success: res => {
if (res.confirm) {
console.log(index);
console.log(this.srcVideo[index]);
deleteFileApi(this.srcVideo[index].split("/")[3]);
this.srcVideo.splice(index, 1);
}
if (this.srcVideo.length == 4) {
this.VideoOfImagesShow = false;
} else {
this.VideoOfImagesShow = true;
}
}
});
},
// 上傳 end
}
}
</script>
<style scoped lang="scss">
// 上傳
.update-file {
margin-left: 10rpx;
height: auto;
display: flex;
justify-content: space-between;
flex-wrap: wrap;
margin-bottom: 5rpx;
.del-icon {
width: 44rpx;
height: 44rpx;
position: absolute;
right: 10rpx;
top: 12rpx;
}
.btn-text {
color: #606266;
}
.preview-file {
width: 200rpx;
height: 180rpx;
border: 1px solid #e0e0e0;
border-radius: 10rpx;
}
.upload-box {
position: relative;
width: 200rpx;
height: 180rpx;
margin: 0 20rpx 20rpx 0;
}
.remove-icon {
position: absolute;
right: -10rpx;
top: -10rpx;
z-index: 1000;
width: 30rpx;
height: 30rpx;
}
.upload-btn {
width: 200rpx;
height: 180rpx;
border-radius: 10rpx;
background-color: #f4f5f6;
display: flex;
justify-content: center;
align-items: center;
}
}
.guide-view {
margin-top: 30rpx;
display: flex;
.guide-text {
display: flex;
flex-direction: column;
justify-content: space-between;
padding-left: 20rpx;
.guide-text-price {
padding-bottom: 10rpx;
color: #ff0000;
font-weight: bold;
}
}
}
.service-process {
background-color: #ffffff;
padding: 20rpx;
padding-top: 30rpx;
margin-top: 30rpx;
border-radius: 10rpx;
padding-bottom: 30rpx;
.title {
text-align: center;
margin-bottom: 20rpx;
}
}
.form-view-parent {
border-radius: 20rpx;
background-color: #FFFFFF;
padding: 0rpx 20rpx;
.form-view {
background-color: #FFFFFF;
margin-top: 20rpx;
}
.form-view-textarea {
margin-top: 20rpx;
padding: 20rpx 0rpx;
.upload-hint {
margin-top: 10rpx;
margin-bottom: 10rpx;
}
}
}
.bottom-class {
margin-bottom: 60rpx;
}
.bottom-btn-class {
padding-bottom: 1%;
.bottom-hint {
display: flex;
justify-content: center;
padding-bottom: 20rpx;
}
}
</style>
deleteOssFile.js
import http from "../../utils/httpRequest/http";
// 刪除圖片
export const deleteFileApi = (fileName) =>{
console.log(fileName);
return http.put(`/api/file/upload/${fileName}`);
}
http.js
const baseUrl = 'http://192.168.163.30:9999';
// const baseUrl = 'http://localhost:9999';
const http = (options = {}) => {
return new Promise((resolve, reject) => {
uni.request({
url: baseUrl + options.url || '',
method: options.type || 'GET',
data: options.data || {},
header: options.header || {}
}).then((response) => {
// console.log(response);
if (response.data && response.data.code == 200) {
resolve(response.data);
} else {
uni.showToast({
icon: 'none',
title: response.data.msg,
duration: 2000
});
}
}).catch(error => {
reject(error);
})
});
}
/**
* get 請求封裝
*/
const get = (url, data, options = {}) => {
options.type = 'get';
options.data = data;
options.url = url;
return http(options);
}
/**
* post 請求封裝
*/
const post = (url, data, options = {}) => {
options.type = 'post';
options.data = data;
options.url = url;
return http(options);
}
/**
* put 請求封裝
*/
const put = (url, data, options = {}) => {
options.type = 'put';
options.data = data;
options.url = url;
return http(options);
}
/**
* upLoad 上傳
*
*/
const upLoad = (parm) => {
return new Promise((resolve, reject) => {
uni.uploadFile({
url: baseUrl + parm.url,
filePath: parm.filePath,
name: 'file',
formData: {
openid: uni.getStorageSync("openid")
},
header: {
// Authorization: uni.getStorageSync("token")
},
success: (res) => {
resolve(res.data);
},
fail: (error) => {
reject(error);
}
})
})
}
export default {
get,
post,
put,
upLoad,
baseUrl
}
SpringBoot3 的源碼
FileUploadController.java
package com.zhx.app.controller;
import com.zhx.app.utils.AliOssUtil;
import com.zhx.app.utils.ResultUtils;
import com.zhx.app.utils.ResultVo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;
/**
* @ClassName : FileUploadController
* @Description : 文件上傳相關(guān)操作
* @Author : zhx
* @Date: 2024-03-01 19:45
*/
@RestController
@RequestMapping("/api/file")
public class FileUploadController {
@PostMapping("/upload")
public ResultVo upLoadFile(MultipartFile file) throws Exception {
// 獲取文件原名
String originalFilename = file.getOriginalFilename();
// 防止重復上傳文件名重復
String fileName = null;
if (originalFilename != null) {
fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.indexOf("."));
}
// 把文件儲存到本地磁盤
// file.transferTo(new File("E:\\SpringBootBase\\ProjectOne\\big-event\\src\\main\\resources\\flies\\" + fileName));
String url = AliOssUtil.uploadFile(fileName, file.getInputStream());
return ResultUtils.success("上傳成功!", url);
}
@PutMapping("/upload/{fileName}")
public ResultVo deleteFile(@PathVariable("fileName") String fileName) {
System.out.println(fileName);
if (fileName != null) {
return AliOssUtil.deleteFile(fileName);
}
return ResultUtils.success("上傳失?。?);
}
}
AliOssUtil.java
package com.zhx.app.utils;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
/**
* @ClassName : AliOssUtil
* @Description : 阿里云上傳服務
* @Author : zhx
* @Date: 2024-03-1 20:29
*/
@Component
public class AliOssUtil {
private static String ENDPOINT;
@Value("${alioss.endpoint}")
public void setENDPOINT(String endpoint){
ENDPOINT = endpoint;
}
private static String ACCESS_KEY;
@Value("${alioss.access_key}")
public void setAccessKey(String accessKey){
ACCESS_KEY = accessKey;
}
private static String ACCESS_KEY_SECRET;
@Value("${alioss.access_key_secret}")
public void setAccessKeySecret(String accessKeySecret){
ACCESS_KEY_SECRET = accessKeySecret;
}
private static String BUCKETNAME;
@Value("${alioss.bucketName}")
public void setBUCKETNAME(String bucketName){
BUCKETNAME = bucketName;
}
public static String uploadFile(String objectName, InputStream inputStream) {
String url = "";
// 創(chuàng)建OSSClient實例。
OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY, ACCESS_KEY_SECRET);
try {
// 創(chuàng)建PutObjectRequest對象。
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKETNAME, objectName, inputStream);
// 如果需要上傳時設置存儲類型和訪問權(quán)限,請參考以下示例代碼。
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);
// 上傳文件。
PutObjectResult result = ossClient.putObject(putObjectRequest);
url = "https://" + BUCKETNAME + "." + ENDPOINT.substring(ENDPOINT.lastIndexOf("/") + 1) + "/" + objectName;
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return url;
}
public static ResultVo deleteFile(String objectName) {
// 創(chuàng)建OSSClient實例。
OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY, ACCESS_KEY_SECRET);
try {
// 刪除文件。
ossClient.deleteObject(BUCKETNAME, objectName);
return ResultUtils.success("刪除成功!");
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return ResultUtils.error("上傳失??!");
}
}
文章來源:http://www.zghlxwxcb.cn/news/detail-851185.html
到了這里,關(guān)于SpringBoot3 + uniapp 對接 阿里云0SS 實現(xiàn)上傳圖片視頻到 0SS 以及 0SS 里刪除圖片視頻的操作(最新)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!