javascript 在JS中从HTML输入编码文件

toe95027  于 12个月前  发布在  Java
关注(0)|答案(1)|浏览(78)

我有以下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函数从输入中编码文件。但是,我如何获得这个文件的路径,或者是否有机会以我需要的方式直接编码文件?

gywdnpxw

gywdnpxw1#

首先,您的表单必须具有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.');
    }
  };

相关问题