欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > Vue2实现上传图片到阿里云的OSS对象存储

Vue2实现上传图片到阿里云的OSS对象存储

2025/2/13 3:37:56 来源:https://blog.csdn.net/cuishujian_2003/article/details/145148437  浏览:    关键词:Vue2实现上传图片到阿里云的OSS对象存储

在 Vue 2 项目中,将图片上传到阿里云的 OSS(对象存储)需要几个步骤,包括配置阿里云 OSS、获取上传凭证、在前端进行上传操作等。以下是一个详细的实现步骤:

1. 配置阿里云 OSS

首先,你需要在阿里云 OSS 上创建一个存储桶(Bucket),并配置好相关的权限。

2. 后端获取上传凭证

由于直接暴露 OSS 的 Access Key ID 和 Access Key Secret 到前端是不安全的,所以需要通过后端服务器来获取一个临时的上传凭证(STS Token)。

以下是一个使用 Node.js 和阿里云 SDK 获取上传凭证的示例:

const OSS = require('ali-oss');
const STS = require('ali-oss').STS;const client = new OSS({region: '<your-oss-region>',accessKeyId: '<your-access-key-id>',accessKeySecret: '<your-access-key-secret>',sts: new STS({accessKeyId: '<your-access-key-id>',accessKeySecret: '<your-access-key-secret>',})
});async function getUploadCredentials(bucketName, objectName) {try {const result = await client.stsAssumeRole('<your-sts-role-arn>', '<your-sts-session-name>', 3600);const stsCredentials = {AccessKeyId: result.credentials.AccessKeyId,AccessKeySecret: result.credentials.AccessKeySecret,SecurityToken: result.credentials.SecurityToken,Expiration: result.credentials.Expiration,};const policy = {expiration: new Date(Date.now() + 3600 * 1000).toISOString(), // 1 hourconditions: [['content-length-range', 0, 10485760], // Limit upload size to 10MB['starts-with', '$key', objectName],],};const postObject = await client.postObject(bucketName, objectName, policy);return {...stsCredentials,...postObject,};} catch (error) {console.error('Error getting upload credentials:', error);throw error;}
}// Example usage:
getUploadCredentials('<your-bucket-name>', '${filename}').then(credentials => {console.log(credentials);
}).catch(error => {console.error('Error:', error);
});


3. 前端 Vue 2 实现上传

在 Vue 2 项目中,你可以使用 Axios 或 Fetch 来请求后端接口获取上传凭证,然后使用这些凭证进行文件上传。

以下是一个 Vue 组件的示例:

<template><div><input type="file" @change="handleFileChange" /><button @click="uploadFile">Upload</button></div>
</template><script>
import axios from 'axios';export default {data() {return {file: null,uploadCredentials: null,};},methods: {async handleFileChange(event) {this.file = event.target.files[0];},async fetchUploadCredentials() {try {const response = await axios.get('/api/get-oss-credentials'); // 替换为你的后端接口this.uploadCredentials = response.data;} catch (error) {console.error('Error fetching upload credentials:', error);}},async uploadFile() {if (!this.file || !this.uploadCredentials) {alert('Please select a file and fetch credentials first.');return;}const formData = new FormData();formData.append('key', this.uploadCredentials.key);formData.append('OSSAccessKeyId', this.uploadCredentials.AccessKeyId);formData.append('policy', this.uploadCredentials.policy);formData.append('Signature', this.uploadCredentials.signature);formData.append('success_action_status', '200');formData.append('file', this.file);try {const response = await axios.post(this.uploadCredentials.uploadUrl, formData, {headers: {'Content-Type': 'multipart/form-data',},});console.log('Upload successful:', response.data);} catch (error) {console.error('Error uploading file:', error);}},},async mounted() {// Fetch upload credentials when the component is mountedawait this.fetchUploadCredentials();},
};
</script>

4. 注意事项
  1. 安全性:确保你的后端接口 /api/get-oss-credentials 是安全的,并且只有经过身份验证的用户才能访问。
  2. CORS 配置:在阿里云 OSS 的 Bucket 配置中,配置 CORS(跨域资源共享),允许你的前端域名进行访问。
  3. 错误处理:在实际项目中,应添加更多的错误处理和用户提示。

通过以上步骤,你就可以在 Vue 2 项目中实现从前端上传图片到阿里云 OSS 对象存储。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com