File upload
- A simple batch upload example
my-nodestack-app
├── src
│ ├── pages
│ │ │── upload
│ │ │ │── index.js
│ ├── plugins
│ │ │── upload.js
├── ndsk.config.js
└── package.json
const Path = require('node:path');
const Fs = require('node:fs');
exports.plugin = {
name: 'upload',
register: async (server) =>{
server.route({
method:'POST',
path:'/upload',
options: {
payload: {
output: 'stream',
parse:true,
multipart: true,
maxBytes:1048576 * 1,
timeout:1000 * 60 * 1
}
},
handler:async ({payload},h)=>{
try {
const arr = [];
for(let item in payload){
const file = payload[item];
const buffer = file._data;
const name = file.hapi.filename;
const uploadDir = Path.join(process.cwd(),'static/upload');
Fs.mkdirSync(uploadDir, {recursive: true});
Fs.writeFileSync(Path.join(uploadDir,name),buffer);
arr.push(`http://localhost:3000/static/upload/${name}`)
}
return arr
} catch (error) {
throw error
}
}
})
}
}
import {useState} from 'react'
export default (props)=>{
const [arr,setArr] = useState([])
return (
<html lang="en">
<head>
<title>{props.title}</title>
</head>
<body>
<div>
<input multiple type="file" onChange={(e)=>{
const files = e.target.files;
const formData = new FormData();
for(let i=0;i<files.length;i++){
formData.append(`file${i}`,files[i]);
}
fetch(`/upload`, {
method: 'POST',
body: formData
}).then(async res=>{
setArr(await res.json())
});
}}
/>
</div>
<div>
{
arr.map(src=>{
return (
<img src={src} width={100}></img>
)
})
}
</div>
</body>
</html>
);
}
- Visit http://localhost:3000/upload
- See the documentation for
options.payload
configuration here