将上传的文件存储在状态变量中不起作用。反应

问题描述 投票:0回答:1

我正在尝试将上传的文件存储在状态变量中,一旦用户完成表单的其余部分,我将把该文件发布到数据库。由于某种原因,我的状态不会更新,并且我的状态变量保留为空。我正在调用 onChange 并将其传递给我的 onChange 函数以将文件存储在状态中。我在代码中添加了一些注释。有人可以帮忙吗?

interface PostState {
  file: File
  //i have tried multiple data types for the file variable, still no luck
}

const Form = (props) => {

  const defaultPostState: PostState = {
    file: null,
    //i have also tried setting this to undefined or not setting a default value at all as well
  }

const [postState, setPostState] = useState(defaultPostState)

const onChange = (e) => {
  setPostState({...postState, file: e.target.files[0]})
  //this is what wont work - i have debugged it and logged it, it wont store the target file in file
}

<div className='form-group'>
  <label>Upload file</label>
  <input
    id='file'
    className='form-control-file'
    type='file'
    name='file'
    ref={register}
    onChange={onChange} 
  />
</div>

reactjs typescript file upload state
1个回答
0
投票

很晚了,但希望对某人有帮助。下面发布答案。

您需要将输入包含在

<form></form>
内,并为其指定
enctype
multipart/form-data

因此代码将如下所示:

<form enctype='multipart/form-data' className='form-group'>
  <label>Upload file</label>
  <input
    id='file'
    className='form-control-file'
    type='file'
    name='file'
    ref={register}
    onChange={onChange} 
  />
</form>
© www.soinside.com 2019 - 2024. All rights reserved.