Skip to content

Instantly share code, notes, and snippets.

@NaClYen
Created November 25, 2021 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NaClYen/4e8472ca96a03e4e4ea8fbdb084564aa to your computer and use it in GitHub Desktop.
Save NaClYen/4e8472ca96a03e4e4ea8fbdb084564aa to your computer and use it in GitHub Desktop.
express upload file react
import Express from "express";
import fileUpload from "express-fileupload";
const app = Express();
app.use(
fileUpload({
limits: {
fileSize: 52428800, // 50 MB, 建議設定上限
},
})
);
app.post('/upload', function(req, res) {
let sampleFile;
let uploadPath;
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
// The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
sampleFile = req.files.sampleFile;
uploadPath = __dirname + '/somewhere/on/your/server/' + sampleFile.name;
// Use the mv() method to place the file somewhere on your server
sampleFile.mv(uploadPath, function(err) {
if (err)
return res.status(500).send(err);
res.send('File uploaded!');
});
});
const formData = new FormData()
formData.append('File', selectedFile)
fetch('https://locahost:3000/upload', {
method: 'POST',
body: formData
})
.then(async res => {
const txt = await res.text()
if (res.ok) return txt
else throw new Error(txt)
})
.then(success => console.log(`upload success: ${success}`))
.catch(err => console.error(`upload failed: ${err}`))
<html>
<body>
<form ref='uploadForm'
id='uploadForm'
action='http://localhost:8000/upload'
method='post'
encType="multipart/form-data">
<input type="file" name="sampleFile" />
<input type='submit' value='Upload!' />
</form>
</body>
</html>
// UI組件為
const onUpload = async (ev: ChangeEvent<HTMLInputElement>) => {
const file = ev.target.files?.[0]
if (file) {
const formData = new FormData()
formData.append('File', file)
fetch('https://locahost:3000/upload', {
method: 'POST',
body: formData
})
.then(async res => {
const txt = await res.text()
if (res.ok) return txt
else throw new Error(txt)
})
.then(success => console.log(`upload success: ${success}`))
.catch(err => console.error(`upload failed: ${err}`))
}
}
const Upload = () => <input type='file' onChange={onUpload} />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment