0

I have the following React.js component code:

import React, {ChangeEvent, useState} from "react";
import { Button } from "@mui/material";
function UploadCVButton() {
    const [selectedFile, setSelectedFile] = useState(null);
  
    const handleFileInputChange = (event) => {
      setSelectedFile(event.target.files[0]);
    };
  
    const handleFormSubmit = (event) => {
      event.preventDefault();
      
      const fs = require('fs');
      const base64 = require('base64-js');

      const filepath = '/path/to/your/file'; // Replace with the actual file path

      const fileData = fs.readFileSync(filepath);
      const encoded = base64.fromByteArray(fileData);
      const encodedString = encoded.toString('utf-8');

      $.ajax({
        url: 'url',        
        method: 'post',            
        dataType: 'json',          
        data: {encoded: encoded},     
        success: function(data){  
             alert(data); 
        }
       });
    };
  
    return (
      <form onSubmit={handleFormSubmit}>
        <label htmlFor="file-input">Choose a file:</label>
        <input
          id="file-input"
          type="file"
          accept=".jpg, .jpeg, .png, .pdf"
          onChange={handleFileInputChange}
        />
        <Button type="submit">Upload</Button>
      </form>
    );
}

I need the handleFormSubmit function to encode the file from input. But how do I get this file's path, or is there an opportunity to encode the file in the way I need directly?

3
  • 1
    You shouldn't need the path, the file input gives you access to the file itself. It looks like you're trying to mix client-side code (React, a UI) and server-side code (node fs module) here, which won't work. (And the mix of React and jQuery sounds like a path to the dark side as well...) What's the actual goal here? Commented Jun 23, 2023 at 16:19
  • @David 1) so how do I encode the file without the path parameter? Should I just put the file itself in base64.fromByteArray("file here?")? 2) What's bad in mixing JQuery and React?) Commented Jun 23, 2023 at 16:34
  • 1
    (1) Are you just looking for something like this? (2) Loading the entire jQuery library just to make an AJAX request is simply an unnecessary bloating of code and resources. The native fetch API already does this. And using jQuery at all will make it very tempting to use it more, such as to interact directly with the DOM. Which will very easily lead to a variety of bugs in a React application. Commented Jun 23, 2023 at 16:38

1 Answer 1

0

first of all your form must have the enctype="multipart/form-data"

<form onSubmit={submitPost} encType="multipart/form-data">
  // your form here
</form>

then create an handler for the file upload

const handleFileInputChange = (event) => {
  setSelectedFile(event.target.files[0]);
};

const uploadFile = async (file) => {
    const formData = new FormData();
    formData.append('your_key_here', file);

    try {
      const response = await fetch(
        'your-endpoint-for-file-upload.com',
        {
          method: 'POST',
          body: formData,
        }
      );
      return await response.json();
    } catch (error) {
      console.error('File upload failed:', error);
    }
  };

and then the onSubmit

const submitPost = async (e) => {
    e.preventDefault();

    if (selectedFile) {
      try {
        const uploadedUrl = await uploadFile(selectedFile);
        // ...add the uploaded url to the form state object
        // send all with a POST REQUEST
      } catch (error) {
        console.error('File upload failed:', error);
      }
    } else {
      console.error('No file selected.');
    }
  };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.