我有一个表单,并尝试在上传文件时调用我的 api。目前,它仅在用户单击提交按钮时才起作用。我怎样才能让它用handleFileChange调用我的api?获取请求仅适用于handleSubmit 函数。这是我的 html:
<form className={styles['resume-form']} onSubmit={handleSubmit}>
<div className="relative">
<input
type="file"
accept=".pdf, .doc, .docx"
id="fileInput"
className="hidden"
onChange={handleFileChange}
/>
<label
htmlFor="fileInput"
className="bg-yellow-500 text-white py-2 px-4 rounded cursor-pointer hover:bg-yellow-600"
>
Choose a file
</label>
</div>
<button type="submit" id="reviewer" className={styles['submit-button']}>Submit</button>
</form>
这是我的JavaScript代码:
const handleFileChange = async (e) => {
setResumeFile(e.target.files[0]);
console.log("test")
try {
const formData = new FormData();
console.log("test1")
formData.append('resume', resumeFile);
const response = await fetch('/api/analyze_resume', {
method: 'POST',
body: formData,
headers: {
// Note: No need to set 'Content-Type' for FormData as it is automatically set
},
});
const responseData = await response.json();
setReviewResult(responseData);
} catch (error) {
console.error('Error submitting resume:', error);
}
};
const handleFileUpload = async (file) => {
setResumeFile(file);
e.preventDefault();
try {
const formData = new FormData();
formData.append('resume', resumeFile);
const response = await fetch('/api/analyze_resume', {
method: 'POST',
body: formData,
headers: {
// Note: No need to set 'Content-Type' for FormData as it is automatically set
},
});
const responseData = await response.json();
setReviewResult(responseData);
} catch (error) {
console.error('Error submitting resume:', error);
}
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
const formData = new FormData();
formData.append('resume', resumeFile);
const response = await fetch('/api/analyze_resume', {
method: 'POST',
body: formData,
headers: {
// Note: No need to set 'Content-Type' for FormData as it is automatically set
},
});
const responseData = await response.json();
setReviewResult(responseData);
} catch (error) {
console.error('Error submitting resume:', error);
}
};
您可以将
e.target.files[0]
用作:
formData.append('resume', e.target.files[0]);
而不是将其设置为某种状态并使用它。