admin管理员组

文章数量:1330594

I'm attempting to use formData with React to store an image file and send to a backend service with Axios.

This is my ponent:

<Dragger
        ref={el}
        type="file" 
        name='file'
        multiple={true}
        onChange={(event) => {
            uploadFile(event.file)
        }}
>
    <p className="ant-upload-drag-icon">
        <InboxOutlined />
    </p>
    <p className="ant-upload-text">
        Click or drag file to this area to upload
    </p>
    <p className="ant-upload-hint">
        Once selected, the file will automatically be uploaded.
    </p>
</Dragger>

This is how I'm accessing formData before I send it to the API:

const uploadFile = file => {
    const formData = new FormData()
    formData.append('file', file)
    // api request ...
}

This does not work.

I've seen other implementations where people use event.target.files[0]; I've tested this, and this does work.

Is there a way to make event.file work? Aren't event.file and event.target.file[0] the same?

Edit:

This is the source to the dragger ponent in ant design:

I'm attempting to use formData with React to store an image file and send to a backend service with Axios.

This is my ponent:

<Dragger
        ref={el}
        type="file" 
        name='file'
        multiple={true}
        onChange={(event) => {
            uploadFile(event.file)
        }}
>
    <p className="ant-upload-drag-icon">
        <InboxOutlined />
    </p>
    <p className="ant-upload-text">
        Click or drag file to this area to upload
    </p>
    <p className="ant-upload-hint">
        Once selected, the file will automatically be uploaded.
    </p>
</Dragger>

This is how I'm accessing formData before I send it to the API:

const uploadFile = file => {
    const formData = new FormData()
    formData.append('file', file)
    // api request ...
}

This does not work.

I've seen other implementations where people use event.target.files[0]; I've tested this, and this does work.

Is there a way to make event.file work? Aren't event.file and event.target.file[0] the same?

Edit:

This is the source to the dragger ponent in ant design: https://github./ant-design/ant-design/tree/master/ponents/upload

Share Improve this question edited Aug 22, 2021 at 4:07 kmoser 9,3083 gold badges26 silver badges44 bronze badges asked Oct 24, 2020 at 17:28 schoenblschoenbl 7232 gold badges14 silver badges31 bronze badges 2
  • Can you post the source code for Dragger? Or if it is part of a react library, a link to the ponent docs? It is tough to help you with using the onChange function if we can't see it's signature. – Zacx Commented Oct 24, 2020 at 17:31
  • @Zacx Definitely. Just edited the original post; it's a ponent from ant design. – schoenbl Commented Oct 24, 2020 at 17:44
Add a ment  | 

2 Answers 2

Reset to default 2

I used this ponent recently so I can explain how I got it working. Instead of using onChange to upload your file, you can simply use the action prop of the Dragger ponent to tell it where to send the file. Then you can use onChange to update your UI when the upload is plete.

<Upload.Dragger
  action={'/myImageRoute'}
  beforeUpload={beforeUpload}
  accept='.png,.jpg,.jpeg,.webp'
  withCredentials={true}
  onChange={({ file }) => file.status === 'uploading' ? setLoading(true) : setLoading(false)}
/>

Synthetic Events in React

Files are actually stored on the element itself in the DOM, so to access it you must access the target of the event and then its files attribute. The MDN docs on files has more information, so just access event.target.files and you should be able to find your file. This is assuming you're handling React's Synthetic Event.

<Dragger
        ref={el}
        type="file" 
        name='file'
        multiple={true}
        onChange={(event) => {
            uploadFile(event.target.files[0])
        }}
>

If you are, this simple fix should make it easy enough, but if you're looking for the React Synthetic Event you'll notice there's not a file property or event. You'd have to use a library(which it looks like you might be) to handle it that way, and if you are you'd want to read that library's documentation about its file property on the custom onChange interface it's using.

The Custom Event you're handling

To me it looks like you're using Ant Design's Dragger and if that's the case I'd take a closer look at their example and pare it to yours. Below I have copied their onChange handler for their Dragger example:

  onChange(info) {
    const { status } = info.file;
    if (status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (status === 'done') {
      message.success(`${info.file.name} file uploaded successfully.`);
    } else if (status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  }

If you look at their example which I linked too, it looks like you might not be utilizing it in the way you're expecting. This is more for information. You should look at the example and at the action property.

const props = {
  name: 'file',
  multiple: true,
  action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  onChange(info) {
    const { status } = info.file;
    if (status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (status === 'done') {
      message.success(`${info.file.name} file uploaded successfully.`);
    } else if (status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  },
};

Your files should just upload to action if you look at the props in the example itself. Try setting that and then checking on your server to see if it's getting the file. Since it does look like you're using the Ant Design element, this should be what you're looking for.

The Difference

Pure React would be a synthetic event, but this is a custom event that Ant Design uses, and you're not properly implementing the library. Take a close look at the example in the Custom Event and implement the action property to get it to upload to your server.

本文标签: javascriptDifference between eventfile and eventtargetfilesStack Overflow