使用预签名的url,客户端可以直接将文件上传到兼容S3的云存储服务器(S3),而无需向用户公开S3凭据。
本示例介绍如何使用MinIO JavaScript库中的preignedputobject API来生成一个预签名的URL。
通过一个JavaScript示例演示了这一点,其中Express Node.js服务器公开了一个端点来生成一个预签名的URL,客户端web应用程序使用该URL将文件上传到MinIO服务器。
- 创建服务器
- 创建客户端Web应用程序
创建服务器
const Minio = require('minio')
var client = new Minio.Client({
endPoint: 'play.min.io',
port: 9000,
useSSL: true,
accessKey: 'Q3AM3UQ867SPQQA43P2F',
secretKey: 'zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG'
})
// express is a small HTTP server wrapper, but this works with any HTTP server
const server = require('express')()
server.get('/presignedUrl', (req, res) => {
client.presignedPutObject('uploads', req.query.name, (err, url) => {
if (err) throw err
res.end(url)
})
})
server.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
})
server.listen(8080)
该服务器由Express Node.js服务器组成,该服务器公开了一个名为/presignedUrl的端点。该端点使用Minio。客户机对象来生成一个短期的、预签名的URL,该URL可用于将文件上传到Mino服务器。
创建客户端Web应用程序
<input type="file" id="selector" multiple>
<button onclick="upload()">Upload</button>
<div id="status">No uploads</div>
<script type="text/javascript">
// `upload` iterates through all files selected and invokes a helper function called `retrieveNewURL`.
function upload() {
// Get selected files from the input element.
var files = document.querySelector("#selector").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Retrieve a URL from our server.
retrieveNewURL(file, (file, url) => {
// Upload the file to the server.
uploadFile(file, url);
});
}
}
// `retrieveNewURL` accepts the name of the current file and invokes the `/presignedUrl` endpoint to
// generate a pre-signed URL for use in uploading that file:
function retrieveNewURL(file, cb) {
fetch(`/presignedUrl?name=${file.name}`).then((response) => {
response.text().then((url) => {
cb(file, url);
});
}).catch((e) => {
console.error(e);
});
}
// ``uploadFile` accepts the current filename and the pre-signed URL. It then uses `Fetch API`
// to upload this file to S3 at `play.min.io:9000` using the URL:
function uploadFile(file, url) {
if (document.querySelector('#status').innerText === 'No uploads') {
document.querySelector('#status').innerHTML = '';
}
fetch(url, {
method: 'PUT',
body: file
}).then(() => {
// If multiple files are uploaded, append upload status on the next line.
document.querySelector('#status').innerHTML += `<br>Uploaded ${file.name}.`;
}).catch((e) => {
console.error(e);
});
}
</script>
客户端web应用程序的用户界面包含一个选择器字段,允许用户选择要上传的文件,以及一个调用onclick处理程序upload的按钮:
发表回复