【发布时间】:2019-04-20 01:36:26
【问题描述】:
我正在使用 multer 从我的 react 客户端上传图片。所有的图像都被存储了,只是没有显示出来。图像正在被存储,但没有出现在反应中。设置在状态只是不显示。我可以在后端的图像文件夹中看到它们,所以我知道 multer 正在工作。
这是我的反应组件
class AddNewDish extends Component {
constructor(props){
super(props)
this.state = {
name: '',
imageUrl: '',
description: ''
}
}
createDishHandler = (event) => {
event.preventDefault()
const fd = new FormData();
fd.append('name', this.state.name)
fd.append('imageUrl', this.state.imageUrl, this.state.imageUrl.name)
fd.append('description', this.state.description)
axios.post('http://localhost:8080/add-new-dish', fd,)
.then(res => {
console.log(res, 'res')
})
this.props.history.push('/')
}
onChange = (e) => {
switch(e.target.name) {
case 'imageUrl':
this.setState({imageUrl: e.target.files[0]});
break;
default:
this.setState({[e.target.name]: e.target.value})
}
console.log(e)
}
render () {
console.log(this.state.imageUrl, 'in imgUrl')
return (
<div>
<form onSubmit={this.createDishHandler}>
<input
label='Name'
onChange={this.onChange}
name='name'
type='text'
placeholder='Enter Dish Name'
value={this.state.name}
/>
< input
label='Dish Image'
onChange={this.onChange}
name='imageUrl'
type='file'
placeholder='Enter Dish Image'
// value={this.state.imageUrl}
/>
<input
label='Description'
onChange={this.onChange}
name='description'
placeholder='Enter Dish Description'
type='text'
value={this.state.description}
/>
<img src={this.state.imageUrl}/>
<button>Submit Dish</button>
</form>
</div>
)
}
};
export default AddNewDish
一个后端
const multer = require('multer');
const fileStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'public')
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString() + '-' + path.extname(file.originalname))
}
});
const fileFilter = (req, file, cb) => {
if(
file.mimetype === 'image/png' ||
file.mimetype === 'image/jpg' ||
file.mimetype === 'image/jpeg'
) {
cb(null, true)
} else {
cd(null, false)
}
}
exports.upload = multer({
storage: fileStorage,
fileFilter: fileFilter
})
.single('imageUrl')
这就是我如何称呼我的路线
exports.postADish = async ( req, res,) => {
console.log(req.file, 'in req.file')
try {
const { name, description } = req.body;
const imageUrl = req.file.path
const newDish = await dish.postNewDish({name, description, imageUrl})
res.status(201).json(`new dish added`)
} catch (err) {
res.status(500).json(`Error posting dish`)
console.log(err)
}
};
我如何使用上传中间件
router.post('/add-new-dish', dishController.upload, dishController.postADish);
公开文件夹
app.use('/public', express.static('public'))
这就是我尝试在前端的索引路由中显示图像的方式
class App extends Component {
constructor () {
super()
this.state = {
data: []
}
}
componentDidMount() {
axios
.get(`http://localhost:8080/`)
.then(res => {
console.log(res, 'response')
this.setState({
data: res.data.dishData
})
})
.catch(err => {
console.log(err)
})
}
render() {
console.log(this.state.data)
return (
<div className="App">
<Nav
<Route
exact path ='/'
render={props =>
<Home
{...props}
dishes={this.state.data}
/>
}
/>
我的状态是这样的
{id: 7, name: "test dish", imageUrl: "public/2019-04-20T22:52:09.900Z-20190411_112505.jpg", description: "test description"}
我正在取回 imageUrl 并像这样在 home 组件中使用它
const Home = (props) => {
return (
<DishWrapper>
<DishContent>
{props.dishes.map(dish => {
console.log(dish, 'in dish')
return (
<Dish key={dish.id}>
<h3>{dish.name}</h3>
<img src={ `public/${dish.imageUrl}`} alt={dish.name}/>
<h5>{dish.description}</h5>
</Dish>
)
})}
</DishContent>
</DishWrapper>
)
};
export default Home
在后端我的 get 看起来像这样
exports.getDishes = async (req, res) => {
try {
const dishData = await dish.getDishes()
if(!dishData) {
res.status(404).json(`No dishes available at this time`)
} else {
res.status(200).json({
dishData,
})
}
} catch (err) {
res.status(500)
console.log(err)
}
};
【问题讨论】:
-
在我看来,您在 axios 调用中将一个 imageUrl 从您的组件发送到 multer,然后在上传之前将日期字符串添加到文件名中,对吗?如果是这样,您需要在 res 中返回该文件名并将其用作图像 src。当您在路由中控制台记录 req.file 时会得到什么,您是否获得更新的文件名?
-
这是我在 req.file 控制台日志
{ fieldname: 'imageUrl', originalname: '20190411_112542.jpg', encoding: '7bit', mimetype: 'image/jpeg', destination: 'images', filename: '2019-04-20T01:00:07.965Z-.jpg', path: 'images/2019-04-20T01:00:07.965Z-.jpg', size: 2361225 }中得到的内容@ -
所以在我的 .json 中我应该发送 imageUrl?
-
所以我只是注意到上传图片后您将页面更改为索引。您是否在单击提交按钮之前或之后查看图像时遇到问题?如果它在你之前,你需要采取不同的方法,如果它在之后,那么你需要将图像文件名发送回你的 res.
-
我在查看之前和之后的图像时都遇到了问题
标签: mysql node.js reactjs multer