Created
May 30, 2025 13:48
-
-
Save sunmeat/356088fcdb6d8663cb5d0f915038b47c to your computer and use it in GitHub Desktop.
черновик работа с файлами
This file contains hidden or 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
import { useState } from 'react'; | |
import './App.css'; | |
function App() { | |
const [file, setFile] = useState(null); | |
const [preview, setPreview] = useState(null); | |
const [message, setMessage] = useState(''); | |
const handleFileChange = (e) => { | |
const selectedFile = e.target.files[0]; | |
setFile(selectedFile); | |
const reader = new FileReader(); | |
reader.onload = () => setPreview(reader.result); | |
reader.readAsDataURL(selectedFile); | |
}; | |
const uploadFile = async () => { | |
if (!file) return; | |
const formData = new FormData(); | |
formData.append('image', file); | |
try { | |
const response = await fetch('http://your-server.com/api/upload.php', { | |
method: 'POST', | |
body: formData, | |
}); | |
const data = await response.json(); | |
setMessage(data.success ? 'Файл загружен!' : 'Ошибка: ' + data.error); | |
} catch (err) { | |
setMessage('Ошибка сервера'); | |
} | |
}; | |
return ( | |
<div className="container"> | |
<h1>Загрузка изображения</h1> | |
<input type="file" accept="image/*" onChange={handleFileChange} /> | |
{preview && <img src={preview} alt="Предпросмотр" className="preview" />} | |
<button onClick={uploadFile} disabled={!file}>Загрузить</button> | |
{message && <p>{message}</p>} | |
</div> | |
); | |
} | |
export default App; | |
.container { | |
max-width: 800px; | |
margin: 0 auto; | |
padding: 20px; | |
} | |
.preview { | |
max-width: 200px; | |
margin: 10px 0; | |
} | |
button { | |
padding: 10px; | |
background-color: #007bff; | |
color: white; | |
border: none; | |
cursor: pointer; | |
} | |
button:disabled { | |
background-color: #ccc; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment