oss获取桶内所有文件,并将结果传给前端表单,给出前后端的实现代码
时间: 2024-10-22 08:28:43 浏览: 25
在阿里云OSS(Object Storage Service)中获取存储桶内的所有文件并传递给前端,通常涉及后端服务通过API查询文件列表,然后前端通过Ajax请求接收数据并展示。以下是前后端的一个简单示例:
**后端(Node.js + AWS SDK for JavaScript in Node.js)**
```javascript
const { OSS } = require('ali-oss');
// 创建OSS实例
const client = new OSS({
region: 'your-region', // 替换为实际区域
accessKeyId: 'your-access-key-id',
accessKeySecret: 'your-access-key-secret',
bucket: 'your-bucket-name'
});
async function listFiles() {
try {
const files = await client.listObjects();
return files.objects.map(file => ({
key: file.key,
lastModified: file.lastModified.toISOString(),
size: file.size
}));
} catch (error) {
console.error('Error listing objects:', error);
throw error;
}
}
module.exports.listFiles = listFiles;
```
**前端(JavaScript, Axios用于发起Ajax请求)**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<form id="fileListForm">
<ul id="filesList"></ul>
</form>
<script>
async function fetchData() {
const response = await axios.get('/api/listFiles');
if (response.data && response.data.length > 0) {
let fileListHTML = '';
response.data.forEach(file => {
fileListHTML += `<li><a href="${file.key}">${file.key}</a> - Last Modified: ${file.lastModified}, Size: ${file.size} bytes</li>`;
});
document.getElementById('filesList').innerHTML = fileListHTML;
} else {
console.log('No files found.');
}
}
fetchData(); // 初始加载文件列表
</script>
</body>
</html>
```
阅读全文