Created
January 1, 2024 10:59
-
-
Save Somtuzy/7917766f22bb5c2f1394afe96ee080b4 to your computer and use it in GitHub Desktop.
This is a simple React template for uploading files showing the component and page.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// components/FileUpload.js | |
import React, { useState } from 'react'; | |
import axios from 'axios'; | |
const FileUpload = () => { | |
const [selectedFile, setSelectedFile] = useState(null); | |
const handleFileChange = (event) => { | |
setSelectedFile(event.target.files[0]); | |
}; | |
const handleFileUpload = async () => { | |
if (selectedFile) { | |
const formData = new FormData(); | |
formData.append('avatar', selectedFile); // 'avatar' is the name used for the file in form data | |
try { | |
// Send the file to your backend using Axios or fetch | |
const response = await axios.post('your-backend-upload-endpoint', formData); | |
console.log(response.data); // Handle the response from the backend | |
} catch (error) { | |
console.error('Error uploading file:', error); | |
} | |
} else { | |
console.warn('No file selected.'); | |
} | |
}; | |
return ( | |
<div> | |
<input type="file" name="avatar" onChange={handleFileChange} /> | |
<button onClick={handleFileUpload}>Upload File</button> | |
</div> | |
); | |
}; | |
export default FileUpload; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// pages/upload.js | |
import React from 'react'; | |
import FileUpload from '../components/FileUpload'; | |
const UploadPage = () => { | |
return ( | |
<div> | |
<h1>Upload Avatar</h1> | |
<FileUpload /> | |
</div> | |
); | |
}; | |
export default UploadPage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment