我在一个网站上工作,以增加服装项目和显示它们。我的最终目标是能够创建一个带有标题、描述和多张照片的服装文章。现在,我可以为DB创建一个包含标题和描述的条目,但是该文件总是空的,或者在使用该条目上传时根本没有文件。
这是我目前的设置。
型号>项目型号
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const itemSchema = new Schema({
title: {type: String},
description: {type: String},
files: {type: String} <---I know I dont want this to be string but it wont let me select File of any kind
}, {
timestamps: true
});
module.exports = mongoose.model('Item', itemSchema);
字符串
AdditemForm
import { useState } from "react";
import axios from "axios";
import * as itemsService from '../../utilities/items-service'
export default function AddItemForm() {
const [fullItem, setFullItem] = useState({
title: '',
description: '',
file: ''
});
function handleChange(evt) {
setFullItem({ ...fullItem, [evt.target.name]: evt.target.value });
}
async function handleSubmit(evt) {
evt.preventDefault();
axios.post('/api/items', fullItem)
.then(response => {
// Handle the response (e.g., show success message, update UI, etc.)
console.log('Item uploaded successfully:', response.data);
})
.catch(error => {
// Handle errors (e.g., show error message, etc.)
console.error('Error uploading item:', error);
});
};
return (
<>
<div>This is the AddItemForm page</div>
<div className="form-container">
<form autoComplete="off" encType="multipart/form-data" onSubmit={handleSubmit}>
<label>Title: </label>
<input type="text" name="title" value={fullItem.title} onChange={handleChange} required />
<label>Description: </label>
<input type="text" name="description" value={fullItem.description} onChange={handleChange} required />
<label>File: </label>
<input type="file" name="file" value={fullItem.file} onChange={handleChange} required />
<button type="submit" >Submit</button>
</form>
</div>
</>
)
}
型
然后我的create函数
async function create(req, res) {
try{
const createdItem = await Item.create(req.body);
res.json(createdItem);
} catch(err) {
res.status(400).json(err);
console.log(err)
}
}
型
我已经看了几天的视频,所有的例子都超级简单,但对我不起作用。
从我所看到的,Multer不再工作,或者至少我不能让它和我的react版本一起玩。
我也尝试过使用formData将项目发送到DB,但当我这样做时,Mongo根本没有得到任何字段。这是备用additem页
import React, { useState } from 'react';
import axios from 'axios';
const ItemUpload = () => {
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [selectedImage, setSelectedImage] = useState(null);
const handleTitleChange = (event) => {
setTitle(event.target.value);
};
const handleDescriptionChange = (event) => {
setDescription(event.target.value);
};
const handleFileSelect = (event) => {
const file = event.target.files[0];
setSelectedImage(file);
};
const handleUpload = () => {
const formData = new FormData();
formData.append('title', title);
formData.append('description', description);
formData.append('image', selectedImage);
axios.post('/api/items', formData)
.then(response => {
// Handle the response (e.g., show success message, update UI, etc.)
console.log('Item uploaded successfully:', response.data);
})
.catch(error => {
// Handle errors (e.g., show error message, etc.)
console.error('Error uploading item:', error);
});
};
return (
<>
<div>
<input type="text" placeholder="Title" value={title} onChange={handleTitleChange} />
<textarea placeholder="Description" value={description} onChange={handleDescriptionChange}></textarea>
<input type="file" onChange={handleFileSelect} />
<button onClick={handleUpload}>Upload</button>
</div>
</>
);
};
export default ItemUpload;
`
型
也尝试过以这种方式提交项目
async function handleSubmit(evt) {
evt.preventDefault();
const newFullItem = await itemsService.createItem(fullItem)
}
型
呼叫
import * as itemsAPI from './items-api';
export async function createItem(itemData) {
const newItem = await itemsAPI.createItemRequest(itemData);
return newItem;
}
型
呼叫
import sendRequest from "./send-request";
const BASE_URL = '/api/items';
export function createItemRequest(itemData) {
const newItem = itemData
return sendRequest(BASE_URL, 'POST', newItem);
}// send-request.js
export default async function sendRequest(url, method = 'GET', payload = null) {
const options = { method };
if (payload) {
options.headers = { 'Content-Type': 'application/json' };
options.body = JSON.stringify(payload);
}
const res = await fetch(url, options);
// res.ok will be false if the status code set is not 2xx
if (res.ok) return res.json();
throw new Error('Bad Request');
}
型
1条答案
按热度按时间qnakjoqk1#
这是我如何使用multer进行单个文件上传。我相信你可以破译它,并适应处理多个图像:
React组分:
字符串
控制器:
型
路线:
型
中间件:
型