在 JS 中从 HTML 输入编码文件

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

我有以下 React.js 组件代码:

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>
    );
}

我需要

handleFormSubmit
函数来对输入的文件进行编码。但是我如何获取这个文件的路径,或者是否有机会直接按照我需要的方式对文件进行编码?

javascript reactjs base64 encode
1个回答
0
投票

首先,您的表单必须具有 enctype="multipart/form-data"

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

然后创建文件上传的处理程序

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);
    }
  };

然后是 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.');
    }
  };
© www.soinside.com 2019 - 2024. All rights reserved.