我希望用户从他们的计算机"上传"一个文件,将其存储在浏览器中(我想(并显示图像,而无需将其发送到服务器。基本上,我希望这种情况发生(网站上的例子(:https://www.javascripture.com/FileReader
这本身就有效,但我使用的是react dropzone,它不起作用。
我的代码:
import React, { useCallback, useState } from "react";
import { useDropzone } from "react-dropzone";
import styles from "./dropzone.module.css";
import ImageZone from "../imagezone";
export default function Dropzone() {
const [path, setPath] = useState("");
const openFile = () => {
const reader = new FileReader();
reader.onload = () => {
const dataURL = reader.result;
setPath(dataURL);
};
};
const onDrop = useCallback(acceptedFiles => {
openFile();
}, []);
const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });
return (
<div className={styles.mycontainer}>
<div className={styles.dropzone} {...getRootProps()}>
<input {...getInputProps()} />
{isDragActive ? (
<p>Drop the files here ...</p>
) : (
<p>Drag 'n' drop some files here, or click to select files</p>
)}
</div>
<ImageZone src={path}></ImageZone>
</div>
);
}
对onDrop回调返回的文件使用URL.createObjectURL(file)
。
import React, { useCallback, useState } from "react";
import { useDropzone } from "react-dropzone";
export default function Dropzone() {
const [paths, setPaths] = useState([]);
const onDrop = useCallback(acceptedFiles => {
setPaths(acceptedFiles.map(file => URL.createObjectURL(file));
}, [setPaths]);
const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });
return (
<div>
<div {...getRootProps()}>
<input {...getInputProps()} />
<p>Drop the files here ...</p>
</div>
{paths.map(path =>
<img key={path} src={path} />
}
</div>
);
}
请参阅https://react-dropzone.js.org/#/预览以获取更多信息。
您可以使用文件读取器api读取被丢弃文件的内容,然后将其显示出来。您需要修复onload
回调
const onDrop = useCallback(acceptedFiles => {
const reader = new FileReader();
reader.onload = e => {
const dataURL = e.target.result;
setPath(dataURL);
};
acceptedFiles.forEach(file => reader.readAsArrayBuffer(file))
}, []);
2022年:请参阅本教程https://blog.logrocket.com/create-drag-and-drop-component-react-dropzone/#create-拖放和图像预览功能