You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中用Dropzone与Epub Reader上传提取EPUB封面报错求助

Fixing EPUB Cover Extraction Error with React Dropzone & EpubJS

Got it, let's work through this issue together. The "referenceError: hre..." you're seeing is almost certainly a typo (like misspelling href as hre) or an attempt to access an undefined variable, paired with the core problem of handling EPUB files without relying on the deprecated path/fullPath properties in modern browsers.

Here's a step-by-step solution that properly uses FileReader to process the EPUB file, initializes EpubJS correctly, and extracts the cover:

1. Correctly Read the EPUB File with FileReader

Modern browsers block access to local file paths for security, so we need to read the file content as an ArrayBuffer (which EpubJS can directly use) instead of trying to reference a file path.

2. Initialize EpubJS Book Instance Properly

Instead of passing a file path to EpubJS, pass the ArrayBuffer we get from FileReader, and wait for the book to be fully loaded before accessing metadata like the cover.

3. Extract & Save the Cover

EpubJS returns the cover as an internal URL; we'll convert that to a Blob to save it locally or upload it to a server.

Working Example Code

import { useDropzone } from 'react-dropzone';
import { Book } from 'epubjs';

const EpubCoverExtractor = () => {
  const { getRootProps, getInputProps } = useDropzone({
    accept: '.epub',
    onDrop: async (acceptedFiles) => {
      try {
        const epubFile = acceptedFiles[0];
        if (!epubFile) return;

        // Step 1: Read file as ArrayBuffer
        const fileBuffer = await new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.onload = () => resolve(reader.result);
          reader.onerror = (err) => reject(new Error(`Failed to read file: ${err.message}`));
          reader.readAsArrayBuffer(epubFile);
        });

        // Step 2: Initialize EpubJS Book and wait for it to be ready
        const book = new Book(fileBuffer);
        await book.ready; // Critical: Wait for metadata to load

        // Step 3: Extract and save the cover
        const coverUrl = book.cover;
        if (coverUrl) {
          // Convert internal cover URL to Blob
          const coverBlob = await fetch(coverUrl).then(res => res.blob());
          
          // Create a download link to save the cover
          const downloadLink = URL.createObjectURL(coverBlob);
          const linkElement = document.createElement('a');
          linkElement.href = downloadLink; // Double-check this line for typos!
          linkElement.download = `${epubFile.name.replace('.epub', '')}-cover.jpg`;
          linkElement.click();
          
          // Clean up the object URL to free memory
          URL.revokeObjectURL(downloadLink);
        } else {
          console.log('No cover found in this EPUB file');
        }
      } catch (error) {
        console.error('Error processing EPUB:', error);
        // Debug the reference error specifically
        if (error instanceof ReferenceError) {
          console.log('Check for typos or undefined variables (e.g., "hre" instead of "href") in your code!');
        }
      }
    }
  });

  return (
    <div {...getRootProps({ className: 'dropzone' })}>
      <input {...getInputProps()} />
      <p>Drag & drop an EPUB file here, or click to select one</p>
    </div>
  );
};

export default EpubCoverExtractor;

Key Troubleshooting Tips

  • Fix the Reference Error: The "hre..." message is almost definitely a typo. Check any code where you're setting a URL (like a.href)—you might have accidentally written hre instead of href.
  • Avoid path/fullPath: Make sure nowhere in your code are you trying to access epubFile.path or epubFile.fullPath—these properties are no longer available in modern browsers.
  • Wait for book.ready: Skipping this step will cause errors when trying to access the cover or other metadata, as the book won't have finished loading yet.
  • Verify Dependencies: Ensure you're using the correct EpubJS package: install it with npm install epubjs (FuturePress's EPUB reader is maintained as epubjs on npm).

内容的提问来源于stack exchange,提问作者user2465134

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:04:32