axios postdata在react中不显示图像,而只显示路径url



我已经创建了一个基本的ReactJS应用程序,使用表单和API来执行crud操作。我已经成功地创建了应用程序来执行所有crud操作,但我面临的唯一问题是在表单中添加图像上传字段并上传图像,我只能在控制台和API中看到图像路径,并且我在上传的详细信息的读取页面中显示相同的图像路径。

我已经给出了创建和读取应用程序的代码,请验证它们并帮助我找到正确的解决方案。

Create.js:

import React, { useState } from 'react';
import { Button, Form } from 'semantic-ui-react'
import axios from 'axios';
import { useNavigate} from 'react-router-dom';
import Swal from 'sweetalert2';
function Create() {
let navigate = useNavigate();
const [image, setImage] = useState('');
const [companyName, setCompanyName] = useState('');
const postData = () => {
const url = `https://62a6f21797b6156bff833b05.mockapi.io/CRUD`
if(companyName.length <= 3){
return Swal.fire({
icon: 'error',
title: 'Error',
text: 'All fields are mandatory!',
showConfirmButton: true
})
}else{
axios.post(url, {
image,
companyName
})

.then(() => {
navigate('/company/list');
})
}

}
return (

<div>
<Form className="create-form">
<Form.Field>
<label>Image</label>
<input type="file" accept='image' onChange={(e) => setImage(e.target.value)} />
</Form.Field>
<Form.Field>
<label>Company Name</label>
<input  placeholder='Company Name' onChange={(e) => setCompanyName(e.target.value)}/>
</Form.Field>
<Button color="blue" onClick={postData} type='submit'>Submit</Button>
</Form>
</div>
)
}
export default Create;

Read.js:

import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { Table, List } from 'semantic-ui-react';

function Read() {
const [APIData, setAPIData] = useState([]);

useEffect(() => {
axios.get(`https://62a6f21797b6156bff833b05.mockapi.io/CRUD`)
.then((response) => {
console.log(response.data)
setAPIData(response.data);
})
}, []);
return (
<div>
<Table singleLine>
<Table.Body>
{APIData.map((data) => {
return (
<Table.Row>
<Table.Cell>
<List>
<List.Item>
{data.image}
</List.Item>
<List.Item>
{data.companyName}
</List.Item>
</List>
</Table.Cell>
</Table.Row>
)
})}
</Table.Body>
</Table>
</div>
)
}
export default Read;

凭借我对ReactJS的了解,我觉得问题在于我使用axios发布图像数据的方式。我不太擅长使用axios,所以我可能把axios函数误认为是发布图像。

帮我解决我所面临的问题,用必要的解决方案从axios发布图像数据。

首先,您应该从输入中获得略有不同的文件:

<input type="file" accept='image' onChange={(e) => setImage(e.target.files[0])} />

通过FormData发送文件更容易,所以试试这个:

let data = new FormData();
data.append('file', image);
data.append('name', companyName);
axios.post(url, data);

我不知道你用什么作为后端,但是你也应该处理服务器端。

最新更新