React中用Dropzone与Epub Reader上传提取EPUB封面报错求助
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 writtenhreinstead ofhref. - Avoid
path/fullPath: Make sure nowhere in your code are you trying to accessepubFile.pathorepubFile.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 asepubjson npm).
内容的提问来源于stack exchange,提问作者user2465134

