0

I am building an application that lets users share files between themselves by uploading it to their profiles. To do this, i have a component called AddReport which initializes a title and file state using useState(), and then renders a form with an input for both title and files upload. the input for the title has a value prop of {title}, and since i can not do same for the file input, how do i collect the uploaded file from the form and store it in a new object that has both the title value and the file value so that upon the submission of the form the user inputs can be sent to a database using a useEffect() call with axios?

<form onSubmit={handleUploadSubmit} >
      <div>
        <label>Title</label>
        <input 
        type="text" placeholder="|Add a title " 
        onChange={handleTitle} value={title}
        />
      </div>

      <div>
        <input type="file"  
          onChange={uploadHandler}
        />
        
        <p className='p-2 mx-[70px] text-sm'>Add Report files(PDF, JPG, PNG)</p>

      </div>
      <button
         onClick={handleUploadSubmit}
         >
         <span className='px-[10px] '>Upload Report</span>
      </button> 
    </form> 
Dr. Tech
  • 23
  • 3
  • https://codesandbox.io/s/file-upload-1t0bx7?file=/src/App.js Hope this helps! – DreamBold Jan 12 '23 at 09:45
  • Yes it absolutely helps! and thanks for the extra checks you added too. i am now puzzled by what happens after the upload button is clicked to submit the new formData to the server using fetch(). What if a user needs to download the uploaded file? – Dr. Tech Jan 12 '23 at 11:37
  • You already accepted an answer, I can see – DreamBold Jan 12 '23 at 11:46

2 Answers2

1

Lets say you have two states for title and photo

const [titile, setTitle] = useState("")
const [photo, setPhoto] = useState(null)

you collect the file and title in their respective states with onchange functions

// onchange for file

 const changePhoto = (e) => {
    setPhoto(e.target.files[0]);
  };

now what needs to be used to send a file is a "FormData"

So the fucntion must look like

const handleUploadSubmit = async()=>{
  
let data = new FormData();
  
  data.append("title", title);
  data.append("photo", photo);

  let response = await axios.post('your url", data);
  return response;

}
0

I think you can't mix the json data with your file. But you can do a Base64 encoding. See the following post:

https://stackoverflow.com/a/4083908/14252755

faragos
  • 18
  • 3
  • For anyone who might be looking for how to directly convert the uploaded file into a format that you can save on your json server during development, this worked! – Dr. Tech Jan 12 '23 at 11:40