Загрузка изображения хорошо работает в бэкэнде. Изображение загружается в папку загрузки. Я не могу понять, как перенести его в интерфейс в React при аутентификации.
Вот как я получаю URL
try {
const response = await api.post('/app/upload', data)
const { user } = response.data
return user
} catch (error) {
throw error
}
}
Вот мой UploadImage. js в React
import React from 'react'
import { uploadImage } from '../../services/apiService'
class FileUpload extends React.Component {
constructor(props){
super(props)
this.state = {
created: false,
userId: this.props.userId,
file: null
}
this.onFileChange = this.onFileChange.bind(this)
this.onFileUpload = this.onFileUpload.bind(this)
}
onFileChange = event => {
this.setState({ file: event.target.files[0] })
}
onFileUpload = async () => {
const { userId, file, poster } = this.state
const imageUpload = { userId, file, poster }
const formData = new FormData()
formData.append("file", file, file.name)
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
await uploadImage(imageUpload, formData, config)
this.setState({ created: true })
}
fileData = () => {
if (this.state.file) {
console.log(this.state.file.name)
return (
<div>
<h2>File Details:</h2>
<p>File Name: {this.state.file.name}</p>
<p>File Type: {this.state.file.type}</p>
<p>
Last Modified:{" "}
{this.state.file.lastModifiedDate.toDateString()}
</p>
</div>
)
} else {
return (
<div>
<br />
<h4>Choose before pressing the Upload button</h4>
</div>
)
}
}
render () {
return (
<div>
<h1>File Upload</h1>
<div>
<input type="file" htmlFor="file" onChange={this.onFileChange} />
<button onClick={this.onFileUpload}>Upload!</button>
</div>
{this.fileData()}
</div>
)
}
}
export default FileUpload
И вот как это выглядит в бэкэнде
const multer = require('multer')
//upload image
const storage = multer.diskStorage({
filename: function (req, file, cb) {
cb(null, Image.name + '-' + Date.now() + '.jpg')
},
destination: function (req, file, cb) {
cb(null, 'uploads/'),
cb(null, `client/src/components/ChildComponents/uploads/`)
}
})
appRouter.get('/upload/:userId', async (req, res) => {
try {
await Image.findOne({
where: {userId: req.params.userId}
})
.then((result) => res.json(result))
} catch (error) {
console.log(error)
}
})
appRouter.get('/upload', async(req,res) => {
try {
await Image.findAll()
.then((result) => res.json(result))
} catch(error) {
console.log(error)
}
})
const upload = multer({ storage: storage })
appRouter.post('/upload', upload.single('file'), async (req, res) => {
try {
await Image.create({
poster: req.file.filename,
userId: req.body.userId
})
.then(r => {
res.send(r.get({ plain: true }))
})
}
catch (error) {
console.log(error)
}
})
Изображение также имеет свою собственную модель и показывать это не имеет значения. Он правильно загружается на почтальоне, но как я могу получить его для загрузки в папку загрузки в React.