[英]How to append multiple files to formData?
I have a form, and I have an input in the form, I upload several images in this input, like so:我有一个表格,我在表格中有一个输入,我在这个输入中上传了几张图片,如下所示:
<input type="file" name="gallery" onChange={imageHandler} required multiple />
And when I output the images in the console, it correctly displays an array of files, but when I append the images, formData.append("gallery", images);
当我 output 控制台中的图像时,它会正确显示文件数组,但是当我 append 图像时,
formData.append("gallery", images);
it is not saved as an array.它没有保存为数组。 It's saved as a File!
它被保存为一个文件!
const [selectedFile, setSelectedFile] = useState();
const [images, setImages] = useState([]);
const token = localStorage.getItem("TOKEN");
const imageHandler = (e) => {
setImages([...images, e.target.files[0]]);
};
useEffect(() => {
images.length && console.log(images);
}, [images]);
console.log(images);
const sendDisease = async (e) => {
e.preventDefault();
console.log(images);
const form = document.getElementById("signUpForm");
const formData = new FormData(form);
formData.append("gallery", images);
console.log(formData);
try {
const api = "https://localhost/golet/api/v1/website/disease/add";
const { data } = await axios.post(api, formData, {
headers: {
headers: { "Content-Type": "multipart/form-data" },
Authorization: `Bearer ${token}`,
},
});
toast.success(data.message, { autoClose: 15000 });
} catch (e) {
console.log(e);
toast.error(e.response.data.error, { autoClose: 15000 });
console.log(e.response.data.error);
}
};
const handleFileSelect = (event) => {
setSelectedFile(event.target.files[0]);
};
return (
<>
<div className="container">
<div className="row">
<form id="signUpForm" className="md-12">
<h2 className="text-center mb-4 font-weight-bold">Add Disease</h2>
<div className="form-row mt-4">
<div className="col-md-6 mb-3">
<label for="">Add Disease</label>
<input
type="text"
className="form-control"
name="unique_name"
required
onChange={(e) => setUniqueName(e.target.value)}
/>
</div>
<div className="col-md-6 mb-3">
<label for="">Title</label>
<input
type="text"
className="form-control"
name="title"
placeholder="Title"
onChange={(e) => setTitle(e.target.value)}
required
/>
</div>
</div>
<div className="form-row">
<div className="col-md-12 mb-3">
<label for="">Gallery</label>
<input type="file" name="gallery" onChange={imageHandler} required multiple />
</div>
</div>
<input type="file" name="image" onChange={handleFileSelect} />
</div>
<button
type="button"
className="btn btn-primary mt-4"
onClick={sendDisease}
>
Submit
</button>
</form>
</div>
</div>
</>
);
Calling new FormData(form)
is enough.调用
new FormData(form)
就足够了。 You don't need to call formData.append("gallery", images)
as the constructor will pick on its own all the images for you.您无需调用
formData.append("gallery", images)
,因为构造函数会自行为您挑选所有图像。 So you may not even need this images
state.所以你甚至可能不需要这张
images
state。
The code below would log all your files if you wanna be sure about it.如果您想确定,下面的代码将记录您的所有文件。 I also created a working Codesandbox for testing.
我还创建了一个用于测试的工作 Codesandbox。
export default function App() {
const handleSubmit = (e) => {
e.preventDefault();
const form = document.getElementById("signUpForm");
const formData = new FormData(form);
console.log(formData.getAll("gallery"));
};
return (
<form id="signUpForm" onSubmit={handleSubmit}>
<input type="file" name="gallery" required multiple />
<button>Sumbit</button>
</form>
);
}
Here in my case Am using ASP.NET Core and its working fine在我的例子中,我使用的是 ASP.NET Core 并且工作正常
images.forEach((image) => {
formData.append('images', image);
});
My Controller我的 Controller
[HttpPost]
public async Task<IActionResult> UpdateProfile([FromForm] UpdateProfileModel updateProfileModel)
{
try
{
await Task.CompletedTask;
return Ok("Done.");
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
My Modal我的模态
public class UpdateProfileModel
{
public List<IFormFile> Images { get; set; } = new List<IFormFile>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.