在我的后端,我有使用 fileUpload 的 server.ts。 我还有使用 multer 的 FileUpload.ts,将图像保存在我的后端服务器中名为“Images”的文件夹中(这有效,在开头保存带有项目 ID 的图像)
这是我的 FileUpload.ts (multer):
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "Images");
},
filename: async (req, file, cb) => {
const vacationId = req.params.id;
const originalName = file.originalname.split(".")[0];
const ext = path.extname(file.originalname);
const fileName = `${vacationId}_${originalName}${ext}`;
console.log(fileName);
console.log(path.join(__dirname, "../Images", fileName));
cb(null, fileName);
},
});
const upload = multer({ storage: storage });
这是我添加假期时的路线,用于路由到 multer 以保存图像:
router.post(
"/:id/upload",
upload.single("image"),
(request: Request, response: Response) => {
response.send("image uploaded successfully");
}
);
这是我的单身假期:
interface singleVacationProps {
id?: number;
destination: string;
vacDesc: string;
vacPrice: number;
vacImg: string;
}
function SingleVacation(props: singleVacationProps): JSX.Element {
console.log(`SingleVac: , ${props.id}_${props.vacImg}`);
return (
<div className="SingleVacation">
<Card>
<CardHeader>{props.destination}</CardHeader>
<CardMedia
component="img"
src={`http://localhost:4000/Images/${props.id}_${props.vacImg}`}
alt={`${props.destination}`}
/>
<CardContent>
<Typography>{props.vacDesc}</Typography>
<Typography>{props.vacPrice}</Typography>
</CardContent>
</Card>
</div>
);
}
这是假期列表:
function VacationList(): JSX.Element {
const [refresh, setRefresh] = useState(false);
const dispatch = useDispatch();
const vacations = useSelector(
(state: { vacations: { vacations: Vacation[] } }) =>
state.vacations.vacations
);
console.log("Vacations: ", vacations);
useEffect(() => {
//use redux
axios
.get("http://localhost:4000/api/v1/vacations/list")
.then((response) => {
dispatch({
type: VacationActionType.downloadVacations,
payload: response.data,
});
console.log("Dispatched action:", {
type: downloadVacations,
payload: response.data,
});
});
// setRefresh(false);
}, [dispatch]);
return (
<div className="VacationList">
<Grid container spacing={2}>
{vacations.map((item) => (
<Grid item xs={12} sm={6} md={4}>
<SingleVacation
key={item.id}
id={item.id}
destination={item.destination}
vacDesc={item.vacDesc}
vacImg={item.vacImg}
vacPrice={item.vacPrice}
/>
</Grid>
))}
</Grid>
</div>
);
}
注意事项: - 当我登录 console.log(
SingleVac: , ${props.id}_${props.vacImg}
) - 它会为这个假期的 img 生成正确的文件名。但是没有显示图像,出现 404 错误,当尝试使用图像的 URL 从浏览器直接访问它时,出现 [object Object]。
- 我的服务器在 localhost:4000 上运行。
-my server.ts 与 Images 文件夹在同一个目录中(都在 backend 文件夹下)
-我还尝试在 /Images 之前添加 /backend 目录 - 没有运气。