SpringBoot3 + uniapp 对接 阿里云0SS 实现上传图片视频到 0SS 以及 0SS 里删除图片视频的操作(最新)

这篇具有很好参考价值的文章主要介绍了SpringBoot3 + uniapp 对接 阿里云0SS 实现上传图片视频到 0SS 以及 0SS 里删除图片视频的操作(最新)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

最终效果图


SpringBoot3 + uniapp 对接 阿里云0SS 实现上传图片视频到 0SS 以及 0SS 里删除图片视频的操作(最新),技术分享,SpringBoot,项目踩坑日记,uni-app,阿里云,音视频文章来源地址https://www.toymoban.com/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, // 页面图片或视频数量超出后,拍照按钮隐藏
 				imageList: [], //存放图片的地址
 				srcVideo: [], //视频存放的地址
 				sourceType: ['拍摄', '相册', '拍摄或相册'],
 				sourceTypeIndex: 2,
 				cameraList: [{
 					value: 'back',
 					name: '后置摄像头',
 					checked: 'true'
 				}, {
 					value: 'front',
 					name: '前置摄像头'
 				}],
 				cameraIndex: 0, //上传视频时的数量
 				//上传图片和视频
 				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 : 文件上传相关操作
 * @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 = "";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY, ACCESS_KEY_SECRET);
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKETNAME, objectName, inputStream);
            // 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。
            // 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) {
        // 创建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("上传失败!");
    }
}

到了这里,关于SpringBoot3 + uniapp 对接 阿里云0SS 实现上传图片视频到 0SS 以及 0SS 里删除图片视频的操作(最新)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 前端上传图片到阿里云(pc端和uniapp小程序)

    官方文档JavaScript客户端签名直传 如果前端是原生的html写的话,就去官网下载示例来看,把文件里面的配置修改成子阿里云的配置就好 客户端进行表单直传到OSS时,会从浏览器向OSS发送带有Origin的请求消息。OSS对带有Origin头的请求消息会进行跨域规则(CORS)的验证,因此需

    2024年02月06日
    浏览(38)
  • 对接YouTube平台实现上传视频——Java实现

    前段时间公司要求对接海外YouTube平台实现视频上传的功能,由于海外文档描述不详细,且本人英语功底不好,过程中踩了很多坑,写出这篇文章出来希望能帮助到有需要的人。 开发环境 :idea 、jdk1.8、maven 开发准备 : 需要一个Google账号 需要登录到Google控制台创建应用开启

    2024年02月11日
    浏览(51)
  • uniapp 上传视频到阿里云之后回显视频获取视频封面

    1.initial-time Number 指定视频初始播放位置,单位为秒(s)。 没什么卵用 2.使用 uni.createVideoContext(“myVideo”, this).seek(number)。 没什么卵用 t_1000 等于截取视频第 1秒作为封面

    2024年04月11日
    浏览(26)
  • 【SpringBoot】文件上传到阿里云

    实例:苍穹外卖 oss 相关配置: application.yml application-dev.yml(这里不用横杠分隔,用驼峰命名也是可以的,SpringBoot会自动转换) 配置属性类AliOssProperties : AliOssUtil : OssConfiguration : 文件上传Controller

    2024年02月03日
    浏览(19)
  • uniapp 上传静态资源-- 微信小程序跟QQ小程序上传静态资源到阿里的对象存储 OSS

    这两天有个需求,要微信小程序跟QQ小程序通过阿里的OSS储存,存放静态资源,遇到了挺多问题,记录一下~~~ 文档:此处 其实这个是被误导了,也怪自己没有仔细看文档,不该有这一步,但是做了就记录一下,正好多了解nodejs环境与浏览器环境 API的差别。 服务器直传里面的

    2024年02月09日
    浏览(28)
  • springboot3 redis 实现分布式锁

    分布式锁介绍 分布式锁是一种在分布式系统中用于控制不同节点上的进程或线程对共享资源进行互斥访问的技术机制。 在分布式环境中,多个服务可能同时访问和操作共享资源,如数据库、文件系统等。为了保持数据的一致性和完整性,需要确保在同一时刻只有一个服务能

    2024年04月16日
    浏览(23)
  • 【SpringBoot3】使用 devtools 实现代码热部署

    Spring Boot DevTools是一组用于提高开发人员生产力,并加速Spring Boot应用程序开发的工具。它提供了一些功能,可以帮助开发人员更快速地构建应用程序,并减少常见的开发问题。 Spring Boot DevTools的主要作用包括: 自动重新加载 :当应用程序中的代码发生变化时,DevTools会自动

    2024年01月16日
    浏览(27)
  • SpringBoot3集成Kafka优雅实现信息消费发送

           首先,你的JDK是否已经是8+了呢?        其次,你是否已经用上SpringBoot3了呢?        最后,这次分享的是SpringBoot3下的kafka发信息与消费信息。        这次的场景是springboot3+多数据源的数据交换中心(数仓)需要消费Kafka里的上游推送信息,这里做数据

    2024年02月02日
    浏览(33)
  • SpringBoot3整合SpringSecurity,实现自定义接口权限过滤

    接口权限过滤是指对于某些接口或功能,系统通过设定一定的权限规则,只允许经过身份认证且拥有相应权限的用户或应用程序进行访问和操作 。这种技术可以有效地保护系统资源和数据安全,防止未授权的用户或程序进行恶意操作或非法访问。通常情况下,接口权限过滤需

    2024年02月08日
    浏览(36)
  • 使用SpringBoot将图片上传至阿里云OSS

    1. 什么是OSS? 官方的解释是这样的:阿里云对象存储OSS(Object Storage Service)是一款海量、安全、低成本、高可靠的云存储服务,提供99.9999999999%(12个9)的数据持久性,99.995%的数据可用性。 官网:对象存储OSS 2. 为什么要使用OSS? 作者认为主要是方便项目上线后的文件业务的处

    2024年02月06日
    浏览(28)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包