我在后端創建了一個 API,它將影像存盤到資料庫中,我創建了一個用于上傳影像的函式,但我得到一個空陣列到我的資料庫。
如果我喜歡這種方式,它作業正常:
<form action='http://localhost:5000/addProduct' method='post' encType='multipart/form-data'>
<input
type="file"
name="images"
multiple
onChange={e => setImages(e.target.files)}
accept="image/png , image/jpeg, image/webp"
/>
<div className=" py-3 text-right ">
<button type="submit" className="inline-flex justify-center py-2 px-4 border border-transparent drop-shadow-md text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">Publish</button>
</div>
</form>
但是,如果我創建一個上傳檔案的函式,而不是采取行動,我得到了一個空陣列。在支持我收到[object FileList]
<form onSubmit={handleUploadImages }>
<input
type="file"
name="images"
onChange={setImages}
multiple
accept="image/png , image/jpeg, image/webp"/>
<button type="submit">Publish</button>
</form>
這是我創建的功能。問題是我想在這里formData.append('images', images.target.files),我想我需要以不同的方式發送檔案但很困惑我該怎么做。
const [images, setImages] = useState<any>()
const [data, setData] = useState()
console.log(data);
const handleUploadImages = (e: any) => {
e.preventDefault()
const formData = new FormData();
formData.append('images', images.target.files) // problem
fetch('http://localhost:5000/addProduct', {
method: 'post',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.insertedId) {
alert('img Added')
}
})
.catch(error => {
console.error('Error:', error);
});
}
uj5u.com熱心網友回復:
你現在的append方法是錯誤的。您必須遍歷檔案并使用images[]密鑰附加它。
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append#example
喜歡:
const formData = new FormData();
const files = images.target.files;
for (let i = 0; i < files.length; i = 1) {
formData.append('images[]', files[i]);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/429097.html
標籤:javascript 数组 反应 数据结构 javascript 对象
