Created
May 30, 2025 12:17
-
-
Save sunmeat/6261bbe91909893b400e25f9ad72ad72 to your computer and use it in GitHub Desktop.
получение файлов + демо POST метода fetch API REACT
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 React, {useState} from 'react'; | |
const styles = { | |
container: { | |
fontFamily: 'Arial, sans-serif', | |
backgroundColor: '#121212', | |
color: '#fff', | |
textAlign: 'center', | |
padding: '2rem', | |
minHeight: '100vh', | |
}, | |
box: { | |
maxWidth: 800, | |
margin: '0 auto', | |
backgroundColor: '#1e1e1e', | |
padding: 20, | |
borderRadius: 10, | |
textAlign: 'left', | |
}, | |
button: { | |
padding: '0.5rem 1rem', | |
margin: '0.5rem', | |
borderRadius: 5, | |
border: 'none', | |
backgroundColor: '#1db954', | |
color: '#fff', | |
cursor: 'pointer', | |
}, | |
buttonHover: { | |
backgroundColor: '#1ed760', | |
}, | |
pre: { | |
backgroundColor: '#2a2a2a', | |
padding: 10, | |
borderRadius: 5, | |
whiteSpace: 'pre-wrap', | |
wordWrap: 'break-word', | |
}, | |
img: { | |
maxWidth: '100%', | |
borderRadius: 10, | |
margin: '1rem 0', | |
}, | |
error: { | |
color: '#ff5555', | |
}, | |
}; | |
const textUrl = | |
'https://gist.githubusercontent.com/sunmeat/5120f241ab0f407138b7c1dc479a2f02/raw/a01e873da40a27bada0192e4e75e632586623329/index.html'; | |
const imageUrl = | |
'https://raw.githubusercontent.com/sunmeat/gallery/main/MyApplication/cats/cat%20(1).jpg'; | |
const jsonObjectUrl = 'https://jsonplaceholder.typicode.com/users/1'; | |
const jsonArrayUrl = 'https://jsonplaceholder.typicode.com/posts'; | |
const postUrl = 'https://petstore.swagger.io/v2/pet'; | |
const FetchExample = () => { | |
// текстовый файл | |
const [textContent, setTextContent] = useState(''); | |
const [textLoading, setTextLoading] = useState(false); | |
const [textError, setTextError] = useState(''); | |
// изображение | |
const [imageBlob, setImageBlob] = useState(null); | |
const [imageLoading, setImageLoading] = useState(false); | |
const [imageError, setImageError] = useState(''); | |
// JSON объект | |
const [jsonObject, setJsonObject] = useState(''); | |
const [jsonObjectLoading, setJsonObjectLoading] = useState(false); | |
const [jsonObjectError, setJsonObjectError] = useState(''); | |
// JSON массив | |
const [jsonArray, setJsonArray] = useState(''); | |
const [jsonArrayLoading, setJsonArrayLoading] = useState(false); | |
const [jsonArrayError, setJsonArrayError] = useState(''); | |
// POST запрос | |
const [postResult, setPostResult] = useState(''); | |
const [postLoading, setPostLoading] = useState(false); | |
const [postError, setPostError] = useState(''); | |
// загрузка текстового файла | |
async function loadText() { | |
setTextLoading(true); | |
setTextError(''); | |
setTextContent(''); | |
try { | |
const response = await fetch(textUrl); | |
if (!response.ok) | |
throw new Error(`Ошибка: ${response.status} ${response.statusText}`); | |
const content = await response.text(); | |
setTextContent(content); | |
} catch (error) { | |
setTextError(error.message); | |
} finally { | |
setTextLoading(false); | |
} | |
} | |
function downloadText() { | |
if (!textContent) return; | |
const blob = new Blob([textContent], {type: 'text/plain'}); | |
const url = URL.createObjectURL(blob); | |
const a = document.createElement('a'); | |
a.href = url; | |
a.download = 'file.txt'; | |
a.click(); | |
URL.revokeObjectURL(url); | |
} | |
// загрузка изображения | |
async function loadImage() { | |
setImageLoading(true); | |
setImageError(''); | |
setImageBlob(null); | |
try { | |
const response = await fetch(imageUrl); | |
if (!response.ok) | |
throw new Error(`Ошибка: ${response.status} ${response.statusText}`); | |
const blob = await response.blob(); | |
setImageBlob(blob); | |
} catch (error) { | |
setImageError(error.message); | |
} finally { | |
setImageLoading(false); | |
} | |
} | |
function downloadImage() { | |
if (!imageBlob) return; | |
const url = URL.createObjectURL(imageBlob); | |
const a = document.createElement('a'); | |
a.href = url; | |
a.download = 'image.jpg'; | |
a.click(); | |
URL.revokeObjectURL(url); | |
} | |
// загрузка JSON объекта | |
async function loadJsonObject() { | |
setJsonObjectLoading(true); | |
setJsonObjectError(''); | |
setJsonObject(''); | |
try { | |
const response = await fetch(jsonObjectUrl); | |
if (!response.ok) | |
throw new Error(`Ошибка: ${response.status} ${response.statusText}`); | |
const json = await response.json(); | |
setJsonObject(JSON.stringify(json, null, 2)); | |
} catch (error) { | |
setJsonObjectError(error.message); | |
} finally { | |
setJsonObjectLoading(false); | |
} | |
} | |
function downloadJsonObject() { | |
if (!jsonObject) return; | |
const blob = new Blob([jsonObject], {type: 'application/json'}); | |
const url = URL.createObjectURL(blob); | |
const a = document.createElement('a'); | |
a.href = url; | |
a.download = 'user.json'; | |
a.click(); | |
URL.revokeObjectURL(url); | |
} | |
// загрузка JSON массива | |
async function loadJsonArray() { | |
setJsonArrayLoading(true); | |
setJsonArrayError(''); | |
setJsonArray(''); | |
try { | |
const response = await fetch(jsonArrayUrl); | |
if (!response.ok) | |
throw new Error(`Ошибка: ${response.status} ${response.statusText}`); | |
const json = await response.json(); | |
setJsonArray(JSON.stringify(json, null, 2)); | |
} catch (error) { | |
setJsonArrayError(error.message); | |
} finally { | |
setJsonArrayLoading(false); | |
} | |
} | |
function downloadJsonArray() { | |
if (!jsonArray) return; | |
const blob = new Blob([jsonArray], {type: 'application/json'}); | |
const url = URL.createObjectURL(blob); | |
const a = document.createElement('a'); | |
a.href = url; | |
a.download = 'posts.json'; | |
a.click(); | |
URL.revokeObjectURL(url); | |
} | |
// POST запрос | |
async function sendPost() { | |
setPostLoading(true); | |
setPostError(''); | |
setPostResult(''); | |
try { | |
const response = await fetch(postUrl, { | |
method: 'POST', | |
headers: {'Content-Type': 'application/json'}, | |
body: JSON.stringify({name: 'Fluffy', status: 'available'}), | |
}); | |
if (!response.ok) | |
throw new Error(`Ошибка: ${response.status} ${response.statusText}`); | |
const json = await response.json(); | |
setPostResult(JSON.stringify(json, null, 2)); | |
} catch (error) { | |
setPostError(error.message); | |
} finally { | |
setPostLoading(false); | |
} | |
} | |
return ( | |
<div style={styles.container}> | |
<div style={styles.box}> | |
<h2>Текстовый файл</h2> | |
<button style={styles.button} onClick={loadText} disabled={textLoading}> | |
{textLoading ? 'Загрузка...' : 'Загрузить текст'} | |
</button> | |
{textContent && ( | |
<> | |
<p>Текстовый файл загружен:</p> | |
<pre style={styles.pre}>{textContent}</pre> | |
<button style={styles.button} onClick={downloadText}> | |
Скачать файл | |
</button> | |
</> | |
)} | |
{textError && <p style={styles.error}>{textError}</p>} | |
</div> | |
<div style={styles.box}> | |
<h2>Изображение</h2> | |
<button style={styles.button} onClick={loadImage} disabled={imageLoading}> | |
{imageLoading ? 'Загрузка...' : 'Загрузить изображение'} | |
</button> | |
{imageBlob && ( | |
<> | |
<p>Изображение загружено:</p> | |
<img | |
style={styles.img} | |
src={URL.createObjectURL(imageBlob)} | |
alt="Загруженное" | |
/> | |
<button style={styles.button} onClick={downloadImage}> | |
Скачать изображение | |
</button> | |
</> | |
)} | |
{imageError && <p style={styles.error}>{imageError}</p>} | |
</div> | |
<div style={styles.box}> | |
<h2>JSON-объект</h2> | |
<button | |
style={styles.button} | |
onClick={loadJsonObject} | |
disabled={jsonObjectLoading} | |
> | |
{jsonObjectLoading ? 'Загрузка...' : 'Загрузить JSON-объект'} | |
</button> | |
{jsonObject && ( | |
<> | |
<p>JSON-объект загружен:</p> | |
<pre style={styles.pre}>{jsonObject}</pre> | |
<button style={styles.button} onClick={downloadJsonObject}> | |
Скачать JSON | |
</button> | |
</> | |
)} | |
{jsonObjectError && <p style={styles.error}>{jsonObjectError}</p>} | |
</div> | |
<div style={styles.box}> | |
<h2>JSON-массив</h2> | |
<button | |
style={styles.button} | |
onClick={loadJsonArray} | |
disabled={jsonArrayLoading} | |
> | |
{jsonArrayLoading ? 'Загрузка...' : 'Загрузить JSON-массив'} | |
</button> | |
{jsonArray && ( | |
<> | |
<p>JSON-массив загружен:</p> | |
<pre style={styles.pre}>{jsonArray}</pre> | |
<button style={styles.button} onClick={downloadJsonArray}> | |
Скачать JSON | |
</button> | |
</> | |
)} | |
{jsonArrayError && <p style={styles.error}>{jsonArrayError}</p>} | |
</div> | |
<div style={styles.box}> | |
<h2>POST-запрос</h2> | |
<button style={styles.button} onClick={sendPost} disabled={postLoading}> | |
{postLoading ? 'Отправка...' : 'Отправить POST'} | |
</button> | |
{postResult && ( | |
<> | |
<p>Питомец успешно добавлен в магазин:</p> | |
<pre style={styles.pre}>{postResult}</pre> | |
</> | |
)} | |
{postError && <p style={styles.error}>{postError}</p>} | |
</div> | |
</div> | |
); | |
}; | |
export default FetchExample; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment