将 docx 上传到页面并仅将第一页显示为图像(REACT)

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

我想做一个网站,让你从你的电脑上传一个 docx 文件,然后只显示 DOCX 的第一页。

为此,我使用了 React 和一些库,但它们不再受支持。我现在正在使用 fileToImage 尝试这个,但我已经尝试使用 react-html-render 等等,但我不能简单地安装它们,因为它们已经过时了:

import React, { useState } from 'react';

function FileUploader() {
  const [fileUrl, setFileUrl] = useState(null);
  const [loading, setLoading] = useState(false);

  const handleFileUpload = async (event) => {
    const file = event.target.files[0];
    setLoading(true);
    try {
      // Convert the file to an image URL
      const fileUrl = await fileToImageUrl(file);
      setFileUrl(fileUrl);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const fileToImageUrl = (file) => {
    return new Promise((resolve, reject) => {
      // Create a new FileReader
      const reader = new FileReader();
      // When the FileReader has finished loading
      reader.onload = (event) => {
        // Create a new image
        const img = new Image();
        // When the image has finished loading
        img.onload = () => {
          // Create a new canvas element
          const canvas = document.createElement('canvas');
          // Set the canvas width and height to match the image
          canvas.width = img.width;
          canvas.height = img.height;
          // Draw the image onto the canvas
          const context = canvas.getContext('2d');
          context.drawImage(img, 0, 0);
          // Convert the canvas to an image URL
          const dataUrl = canvas.toDataURL();
          resolve(dataUrl);
        };
        // When the image has failed to load
        img.onerror = () => {
          reject(new Error('Failed to load image'));
        };
        // Set the image source to the file URL
        img.src = event.target.result;
      };
      // Read the file as a data URL
      reader.readAsDataURL(file);
    });
  };

  return (
    <div>
      <input type="file" accept=".doc,.docx,.pdf" onChange={handleFileUpload} />
      {loading && <p>Loading...</p>}
      {fileUrl && <img src={fileUrl} alt="Uploaded file" />}
    </div>
  );
}

export default FileUploader;

reactjs web docx
© www.soinside.com 2019 - 2024. All rights reserved.