如何使用context.api显示上传的文件内容?



我需要显示我在文件选择器中选择的文件的内容。我已经在导航栏上显示了它的名字,当我点击它的名字时,它把我带到另一个空白标签,我需要在其中显示它的内容。我只需要启用pdf和jpeg文件类型,而不是其他。这个上传组件在一个页面中呈现,然后在app组件中呈现。下面是我的uploader代码:

import React, { useState, useEffect, useContext } from "react";
import { useDropzone } from "react-dropzone";
import Upload from "./pictures/fileUpload.png";
import { fileContext } from "../context/context";
function Uploading() {
const { setFileName } = useContext(fileContext);
const { getRootProps, getInputProps, acceptedFiles } = useDropzone({
noDrag: true,
});
// Logging the selected files to the console. //
console.log(acceptedFiles);
useEffect(() => {
if (acceptedFiles.length === 0) {
console.log("No Uploaded Files. Upload .pdf or .jpeg file !");
} else {
setFileName(acceptedFiles[0].name);
window.localStorage.setItem("fileName", `${acceptedFiles[0].name}`);
}
}, [acceptedFiles]);
return (
<section className="container w-full h-full text-center">
<div {...getRootProps({ className: "dropzone h-full" })}>
<input
{...getInputProps()}
type="file"
/>
<img src={Upload} className="mx-auto cursor-pointer " alt="" />
<label class="text-2xl">Choose Document</label>
</div>
</section>
);
}
export default Uploading;

你可以使用简单的JavaScript。

let file = $('#photo')[0].files[0];
let reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function(e){
let blob = new Blob([e.target.result]);
window.URL = window.URL || window.webkitURL;
let blobURL = window.URL.createObjectURL(blob);
let image = new Image();
image.src = blobURL;
image.onload = function() {
//add the image element to the target container
}
}

对不起,没有完全显示您想要的。我已经展示了如何在文件上传后获取图像元素,然后对其进行操作。

最新更新