简体   繁体   中英

Upload image in react does not return form data values

I want to get form data values uploading images.

 import React from "react"; import "./styles.css"; import { Upload, Button, Form } from "antd"; export default function App() { const normFile = (e) => { const fd = new FormData(); const getFileList = e.fileList.map((i) => { return fd.append("upload", i.originFileObj); }); console.log("formadata values", fd); if (Array.isArray(e)) { return e; } return e && e.fileList; }; return ( <div className="App"> <div> <Form name="form" className="form"> <Form.Item name="upload" className="upload" valuePropName="fileList" getValueFromEvent={normFile} > <Upload name="img" listType="picture"> <Button className="btn">upload images</Button> </Upload> </Form.Item> </Form> </div> </div> ); }

Trying to access console.log("formadata values", fd); i don't get anything there.
Question: How to get form data using my code?
demo: https://codesandbox.io/s/priceless-flower-82tbe?file=/src/App.js:0-883

to see the values in the FormData you must use loop like below:

for (let value of fd.values()) {
   console.log(value);
}

you can also see the value of a certain data by using the key:

console.log(fd.get('key'));

Also be careful for append multi files by a key (in your code = "upload") in loop, your data will override and just one of them append in the end, for uploading multi files by an input you must use the [] after the name of input like below:

const getFileList = e.fileList.map((i) => {
   return fd.append("upload[]", i.originFileObj);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM