Upload from a web page
Let a web page on another domain upload a file directly to OpenFiles.
The upload endpoints allow cross-origin requests, so a page on your website can send a file straight to OpenFiles.
The token is visible to every visitor of the page. Create a separate token for the page with Upload files and one storage only, for example uploads. See Token permissions.
1. Add a file field and a script to your page:
<input type="file" id="file">
<p id="result"></p>
<script>
document.getElementById('file').addEventListener('change', async function() {
const data = new FormData();
data.append('file', this.files[0]);
const res = await fetch('https://files.example.com/upload/uploads/?hostname=1', {
method: 'POST',
headers: { 'x-token': 'PAGE_TOKEN' },
body: data
});
const file = await res.json();
document.getElementById('result').textContent = res.ok ? file.url : 'Upload failed';
});
</script>2. Open the page, choose a file, and the page shows its link.
The answer is the same as in Upload files, for example:
{"id":"JapOAg1di60f","name":"forest.png","size":1591,"type":"image/png","width":400,"height":300,"ext":"png","url":"/files/photos/JapOAg1di60f-rg.png"}When your server can do the upload instead, prefer that and keep the token on the server: see Upload from Node.js.