title: How do I store and send an image file using useState to the backend and then to my database in MERN stack?
body: <p>I'm trying to add a form in which users can add text and images which is then going to be stored on the mongodb database. As of right now, I'm trying to add a section in the form where users can add images. This is the tutorial I'm following: <a href="https://www.tutsmake.com/file-upload-in-mongodb-using-node-js/" rel="nofollow noreferrer">https://www.tutsmake.com/file-upload-in-mongodb-using-node-js/</a></p>
  <p>The tutorial uses this following piece of code to send the image to the backend:</p>
  <pre><code>&lt;form action=&quot;/uploadphoto&quot; enctype=&quot;multipart/form-data&quot; method=&quot;POST&quot;&gt;
          &lt;input type=&quot;file&quot; name=&quot;myImage&quot; accept=&quot;image/*&quot;&gt;
          &lt;input type=&quot;submit&quot; value=&quot;Upload Photo&quot;&gt;
      &lt;/form&gt;
  </code></pre>
  <p>but I am not able to do that since I'm sending the other pieces of data I have using <code>useState</code> like so:</p>
  <pre><code>import { useState } from &quot;react&quot;;
  import { adminSDGOptions } from &quot;./AdminCategoryLists&quot;;
  import { adminAssingmentOptions } from &quot;./AdminCategoryLists&quot;;
  import { keywordsOptions } from &quot;../FilterComponents/CategoryArrays/KeywordsOptions&quot;;
  import Multiselect from &quot;multiselect-react-dropdown&quot;
  import Select from 'react-select';
  
  const ProjectAdminForm = () =&gt; {
      // Adding basic info
      const [sdg, setSDG] = useState('')
      const [goal, setGoal] = useState('')
      const [orginization, setOrginization] = useState('')
      const [source, setSource] = useState('')
      const [location, setLocation] = useState('')
      const [published, setPublished] = useState('')
      const [website_url, setWebsiteURL] = useState('')
      const [assignment_type, setAssignmentType] = useState('')
      const [sharepoint_link, setSharepointLink] = useState('')
      const [statement, setStatement] = useState('')
      const [preview_img, setPreviewImg] = useState([])
      const [error, setError] = useState(null)
  
      // Adding keywords
      const [keywords, setKeywords] = useState([]);
  
  
      const handleSubmit = async (e) =&gt; {
          e.preventDefault() // Prevents refresh of page from happening
          console.log('button clicked')
  
          const project = {sdg, goal, orginization, source, location, published, website_url, assignment_type, keywords, sharepoint_link, statement, preview_img}
          console.log(project)
              
          // Sending form response to backend
          const response = await fetch('/api/projects', {
              method: 'POST',
              body: JSON.stringify(project),
              headers: {
                  'Content-Type': 'application/json'
              }
          })
          const json = await response.json
          
  
          // Checking for error
          if (!response.ok) {
              setError(json.error)
          }
          if (response.ok) {
              // Reset form inputs back to empty string
              setSDG('')
              setGoal('')
              setOrginization('')
              setSource('')
              setLocation('')
              setPublished('')
              setWebsiteURL('')
              setAssignmentType('')
              setKeywords([])
              setSharepointLink('')
              setStatement('')
              
              setError(null)
              alert('Project added!')
              console.log('new project added', json)
          }
      }
  
      return (
          &lt;form className=&quot;create project-form&quot; onSubmit={handleSubmit}&gt;
              &lt;h2 style={{&quot;textAlign&quot;: &quot;center&quot;}}&gt;Add a New Project&lt;/h2&gt;
  
              &lt;hr&gt;&lt;/hr&gt;
  
              &lt;label&gt;Sustainable Development Goal:&lt;/label&gt;
              &lt;Select
                  className=&quot;basic-single&quot;
                  classNamePrefix=&quot;select&quot;
                  placeholder=&quot;Select&quot;
                  name=&quot;color&quot;
                  options={adminSDGOptions}
                  onChange={(selection) =&gt; setSDG(selection.value)}
                  required
              /&gt;
  
              &lt;label&gt;Description:&lt;/label&gt;
              &lt;input 
                  type=&quot;text&quot;
                  onChange={(e) =&gt; setGoal(e.target.value)}
                  value={goal}
                  required
              /&gt;
  
              &lt;label&gt;OPTIONAL - Organization:&lt;/label&gt;
              &lt;input 
                  type=&quot;text&quot;
                  onChange={(e) =&gt; setOrginization(e.target.value)}
                  value={orginization}
              /&gt;
  
              &lt;label&gt;OPTIONAL - Source:&lt;/label&gt;
              &lt;input 
                  type=&quot;text&quot;
                  onChange={(e) =&gt; setSource(e.target.value)}
                  value={source}
              /&gt;
  
              &lt;label&gt;OPTIONAL - Location:&lt;/label&gt;
              &lt;input 
                  type=&quot;text&quot;
                  onChange={(e) =&gt; setLocation(e.target.value)}
                  value={location}
              /&gt;
  
              &lt;label&gt;Published (YEAR ONLY):&lt;/label&gt;
              &lt;input 
                  type=&quot;text&quot;
                  onChange={(e) =&gt; setPublished(e.target.value)}
                  value={published}
                  required
              /&gt;
  
              &lt;label&gt;OPTIONAL - Website URL:&lt;/label&gt;
              &lt;input 
                  type=&quot;text&quot;
                  onChange={(e) =&gt; setWebsiteURL(e.target.value)}
                  value={website_url}
              /&gt;
  
              &lt;label&gt;Assignment Type:&lt;/label&gt;
              &lt;Select
                  className=&quot;basic-single&quot;
                  classNamePrefix=&quot;select&quot;
                  placeholder=&quot;Select&quot;
                  name=&quot;color&quot;
                  options={adminAssingmentOptions}
                  onChange={(selection) =&gt; setAssignmentType(selection.value)}
                  required
              /&gt;
  
              &lt;hr&gt;&lt;/hr&gt;
  
              &lt;label&gt;Enter Keyword(s):&lt;/label&gt;
              &lt;Multiselect
                  className=&quot;multiselect-admin&quot;
                  isObject={false}
                  onRemove={(selection) =&gt; setKeywords(selection)}
                  onSelect={(selection) =&gt; setKeywords(selection)}
                  options={keywordsOptions}
                  required
              /&gt;
  
              &lt;hr&gt;&lt;/hr&gt;
  
              &lt;label&gt;OPTIONAL - Statement (ONLY Assessment Ideas and Discussion Topics):&lt;/label&gt;
              &lt;input 
                  type=&quot;text&quot;
                  onChange={(e) =&gt; setStatement(e.target.value)}
                  value={statement}
              /&gt;
  
              &lt;label&gt;OPTIONAL - Qualtrics Link (ONLY Mini Case Study):&lt;/label&gt;
              &lt;input 
                  type=&quot;text&quot;
                  onChange={(e) =&gt; setSharepointLink(e.target.value)}
                  value={sharepoint_link}
              /&gt;
              
              // THIS IS THE SECTION I'M TRYING TO ADD AND AM NOT SURE HOW TO GO ABOUT DOING SO
              &lt;label&gt;OPTIONAL - Preview image:&lt;/label&gt;
              &lt;input
                  type=&quot;file&quot;
                  name=&quot;preview_img&quot;
                  accept=&quot;image/*&quot;
                  onChange={(e) =&gt; setPreviewImg(e.target.value)}
              /&gt;
              
              &lt;div className=&quot;add-proj&quot;&gt;
                  &lt;button&gt;Add Project&lt;/button&gt;
              &lt;/div&gt;
              
              {error &amp;&amp; &lt;div className=&quot;error&quot;&gt;{error}&lt;/div&gt;}
          &lt;/form&gt;
      )
  }
  
  export default ProjectAdminForm
  </code></pre>
  <p>Right now, when I try uploading a file and sending it, it is just getting sent as a String called this:</p>
  <pre><code>preview_img: &quot;C:\\fakepath\\banner2 (2).jpg&quot;
  </code></pre>
  <p>Does anyone know how I can upload a file using <code>useState</code> similar to how I uploaded the other pieces of Strings in the form above to my Node backend which then gets uploaded to the database?</p>
  <p>This is what my model looks like:</p>
  <pre><code>const mongoose = require('mongoose') 
  
  const Schema = mongoose.Schema
  
  // Project schematic
  const projectSchema = new Schema({
      // general schema templates
  
      // sdg
      sdg: [{
          type: String,
          required: true
      }],
      // description of the project
      goal: {
          type: String,
          required: true
      },
      orginization: {
          type: String,
      },
      source: {
          type: String,
      },
      location: {
          type: String,
      },
      // year published
      published: { 
          type: Number,
          required: true
      },
      website_url: {
          type: String,
      },
      assignment_type: {
          type: String,
          required: true
      },
  
      // array of keywords
      keywords: [{
          type: String,
          required: true
      }],
  
      // assignment specific schema templates
      // ONLY APPLIES TO TIER 1 ASSIGNMENTS, NOT REQUIRED
      statement: {
          type: String
      },
  
      // ONLY APPLIES TO TIER 2 ASSIGNMENTS, NOT REQUIRED
      sharepoint_link: {
          type: String
      },
  
      preview_img: {
          data: Buffer,
          contentType: String
      }
      
  }, { timestamps: true })
  
  module.exports = mongoose.model('Project', projectSchema)
  </code></pre>
  <p>I need a way to somehow upload a file in this portion of my project controller file:</p>
  <pre><code>// create new project
  const createProject = async (req, res) =&gt; {
      const {sdg, goal, orginization, source, location, published, website_url, assignment_type, keywords, sharepoint_link, statement, preview_img} = req.body
      const newProject = new Project({
          sdg: sdg,
          goal : goal,
          orginization : orginization,
          source : source,
          location : location,
          published : published,
          website_url : website_url,
          assignment_type : assignment_type,
          keywords: keywords,
          sharepoint_link : sharepoint_link,
          statement : statement,
          preview_img : preview_img
      });
      try {
          await newProject.save();
      } catch (error) {
          return res.status(400).json({error: error.message})
  
      }
     
      return res.status(201).json({project: newProject});
  }
  </code></pre>
  <p>Does anyone know how I can go about doing this?</p>