我试图使这个功能时,用户可以上传简历和他的形象。
然而,每当我试图同时发送两个到后端,我得到坏的请求错误400。我试图改变的东西,但我似乎不能弄清楚为什么它去400,当我上传图像,或简历,而评论了第一个,或后者,当单独完成它的工作正常。
下面是我的后端代码:
@Post('signup')
@UseInterceptors(FileInterceptor('cv'), FileInterceptor('avatarImage'))
async signUp(
@Body() signupDto: SignupDto,
@UploadedFile() cv: Express.Multer.File,
@UploadedFile() avatarImage: Express.Multer.File,
): Promise<any> {
if (!cv) {
throw new Error('CV file is required.');
}
signupDto.cvFileName = cv.originalname;
signupDto.cvFileBuffer = cv.buffer;
signupDto.cv = await this.fileUploadService.uploadFileCv(
signupDto.cvFileName,
signupDto.cvFileBuffer,
);
if (!avatarImage) {
throw new Error('Avatar Image is required');
}
signupDto.avatarImageName = avatarImage.originalname;
signupDto.avatarImageFileBuffer = avatarImage.buffer;
signupDto.avatarImage = await this.fileUploadService.uploadImage(
signupDto.avatarImageName,
signupDto.avatarImageFileBuffer,
);
return this.userService.createUser(signupDto);
}
我可以分开寄,但不能同时寄。此外,我还提供了获取逻辑片段。
const handleRegistration = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const formData = new FormData();
if (selectedCvFile.length > 0) {
formData.append("cv", selectedCvFile[0] || "");
}
if (selectedImagesForAvatar.length > 0) {
formData.append("avatarImage", selectedImagesForAvatar[0] || "");
}
formData.append("username", formState.username || "");
formData.append("firstName", formState.firstName || "");
formData.append("lastName", formState.lastName || "");
formData.append("password", formState.password || "");
formData.append("email", formState.email || "");
formData.append("phoneNumber", formState.phoneNumber || "");
formData.append("address", formState.address || "");
formData.append("city", formState.city || "");
formData.append("role", formState.role || "");
dispatch({ type: "CLEAR_ALERTS" });
try {
const response = await fetch("http://localhost:3000/auth/signup", {
method: "POST",
body: formData,
});
const data = await response.json();
if (response.ok) {
dispatch({
type: "SHOW_SUCCESS",
payload: `You have registered correctly !`,
});
console.log(data);
localStorage.setItem("token", data.accessToken);
} else {
dispatch({ type: "SHOW_ERROR", payload: response.statusText });
console.error("Registration failed:", response.statusText, response);
// Handle failed registration, e.g., show an error message
}
} catch (error) {
console.error("Error during registration:", error);
// Handle any other errors that may occur during registration
}
};
如果你知道我能做些什么来让它工作,请这样做:)
谢谢
2条答案
按热度按时间yqlxgs2m1#
没有回答您的确切问题,但是为什么不对这个. fileWebadService.uploadFileCv进行两次单独的调用呢?你可以保证.all将它 Package 起来,然后从它返回的数据中得到两个结果。
特别是如果你使用像mongo这样的东西,这甚至可能是首选。
yr9zkbsy2#
我只是从官方文档中实现了解决方案,它起作用了。
从这个问题中得出的主要结论是…阅读文档:)