如何使用 formdata ReactJS 发布图像数组

tim*_*tim 5 javascript multipartform-data reactjs axios

我正在尝试将包含多个图像的对象作为数组发布,如何将图像作为数组附加到 formdata

const onSubmit = async (e) => {

    
    const formData = new FormData(); 
    formData.append("image", values.images);
    formData.append("title", values.title);
    formData.append("price", values.price);
    formData.append("quantity", values.quantity);
    formData.append("id", id);

    try {
      const res = await axios.post(
        "//localhost:4000/products/saveProduct",
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
          },
     /////////////
<form onSubmit={handleSubmit(onSubmit)}>
        <div className="custom-file mb-4">
          <input
            type="file"
            className="custom-file-input"
            name="image"
            multiple
            placeholder="choose file"
            onChange={handleChange}
          />
//////
  const handleChange = (e) => {
    const { type, name } = e.target;
    const getValue = () => {
      if (type === "checkbox") {
        return e.target.checked;
      } else if (type === "select-multiple") {
        return Array.from(e.target.selectedOptions).map(
          (option) => option.value
        );
      } else if (type === "file") {
        for (let i = 0; i < e.target.files.length; i++) {
          e.target.files[i].url = URL.createObjectURL(e.target.files[i]);
        }
        return Array.from(e.target.files);
      }
      return e.target.value;
    };
Run Code Online (Sandbox Code Playgroud)

另外,当我将其发送到后端时,我得到一个空对象作为 req.body

Sza*_*yén 7

您可以将所有图像附加到同一键,例如“images”。然后,您可以在服务器上将请求正文解析为多部分表单数据,并且在访问“图像”时获得文件数组。

for (const image of value.images) {
  formData.append("images", image);
}
Run Code Online (Sandbox Code Playgroud)

不过,如果我没记错的话。当您只附加一个文件时,它不会被解析为服务器上的数组。

另一个解决方案是创建(使用 useRef)或获取(使用 querySelector)对表单元素的引用。然后您可以直接从表单元素创建 formData。

const formData = new FormData(myFormElement);
Run Code Online (Sandbox Code Playgroud)

然后您可以附加要发送的其余数据。