[英]How to upload a file on the frontend?
我遇到了以下問題。 我正在后端開發一個應用程序 whit node.js,在前端開發 React,用戶可以在其中上傳文件。 我在后端的代碼工作正常; 當我使用 postman 時,文件成功上傳且沒有錯誤並插入到我的數據庫中。 現在,當我想在前端執行代碼時,出現以下錯誤:
它說無法讀取文件名,我的反應代碼是下一個:
`
const UploadNomina = () => {
let formData = new FormData()
const uploadFiles = e => {
console.log(e.target.files);
if (e.target && e.target.files[0]) {
formData.append('cfdi', e.target.files[0])
}
}
const insertFiles = async () => {
try {
const token = localStorage.getItem('token')
if (!token) return
const config = {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
}
}
const upLoadFile = await clienteAxios.post('/cfdi-nomina', formData, config)
} catch (error) {
console.error(error);
}
}
return (
<div className={styles.upload}>
<div className={styles.upload_div}>
<div className={styles.upload_title}>
<h1>Carga tu archivo aquí</h1>
<p className={styles.drop_text}>Si carga correctamente tu cfdi podrás ir al modulo de nómina y verlo desde allí</p>
<input type="file" name="files" onChange={uploadFiles}/>
<button
type="button"
onClick={() => insertFiles()}
>Insertar Archivos</button>
</div>
</div>
{msg && <Alerta alerta={alerta} />}
</div>
)
}
export default UploadNomina
`
在后端,這是我的應用程序崩潰的代碼行:
`
const uploadNomina = async (req, res, next) => {
let jsonCfdi = null;
upload(req, res, async(error) => {
try {
if (!error) {
jsonCfdi = await CfdiToJson.parse({
path : __dirname+`/../uploads/${req.file.filename}`
});
`
我試過不成功,我總是得到同樣的錯誤。 我有疑問,因為當我使用 postman 時它運行正常所以我不明白我的問題是在后端還是在前端。
嘗試像這樣使用它。 image[0] 中的格式可能不相同,並且您在后端獲取名稱。
data.append('cfdi', {
uri: e.target.files[0].uri,
name: 'image.jpg',
type: 'image/jpeg',
})
並將標題中的內容類型更改為
'Content-Type': 'multipart/form-data'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.