How do I show uploaded image in React.js - reactjs

So basically I have a field where the user can choose an image to upload, how do I make it so that when the user chooses the image, it displays that image on the screen.
Example, the user uploads the plant2.jpeg , how do i display that image on that same screen. My code is as follows:
import FileBase64 from 'react-file-base64'
//State to handle plant Files
const [plantFile , setPlantFile] = useState(null)
//Handle the input onDone for FileBase64
const handleFiles = (files) => {
setPlantFile(files)
}
<FileBase64
multiple = {false}
onDone = {handleFiles}
/>
The FileBase64 returns an object like below:
{
base64: "data:image/jpeg;base64,/9j/2wCEAAMCAgMCAgMDAwMEAw",
name: "plant2.jpeg",
type: "images/jpeg"
}
Is there a way I can display that image? Anyway I can make that happen?

Related

Why is filepond sending a GET request at my server index when I remove a preloaded file?

Hi I'm using React filepond to upload files to our server and everything works fine for the most part.
The problem is when I have preloaded files, if I try to remove one of them Filepond sends a GET request to http://myserver.domain/12345.jpg
I don't know why this request is sent and this is not even an available endpoint on my server so it always returns an error with status 404.
My filepond instance is configured like this :
export default function FileField({
name,
control,
rules,
defaultValue = null,
isMultiple,
fileTypes,
component_id,
}) {
const [files, setFiles] = useState(defaultValue || []);
// Controller from React-Hook-Form
//(It's used to save the list of files for later use)
const { field } = useController({ name, control, rules, defaultValue });
// Filepond ref
const pond = useRef(null);
const handleChange = () => {
let files = pond.current.getFiles();
// Set the value of the control field
field.onChange(
files.map((f) => {
return { source: f.serverId, options: { type: 'local' } };
})
);
field.onBlur();
};
return (
<div className='px-4 py-4 rounded bg-window-accent'>
<FilePond
ref={(ref) => (pond.current = ref)}
files={files}
onupdatefiles={setFiles}
onprocessfile={handleChange}
onremovefile={handleChange}
required={rules.required.value}
allowMultiple={isMultiple}
server={`/api/files/${component_id}`}
name={'file'}
acceptedFileTypes={fileTypes}
disabled={rules.disabled}
/>
</div>
);
}
When loading the file the correct endpoint is used GET /api/files/12345?load=12345.jpg
It's just when I click on the (X) The file is removed correctly from the input field but there's that additional GET Request that makes no sense...
This error does not happen when a file is reverted after being just uploaded, only happens when the file is preloaded in the files with option type="local".
The error in console
What can I do to stop filepond from sending this extra request ?

How to clip GeoTiff according to shapefile using javascript?

Situation: I am plotting data provided in a GeoTIFF file on a map using Reactjs and geoTiff.js. An example of the GeoTiff files I am using is at the following link: https://drive.google.com/file/d/1yc2Lo5vQrFPAJRe5VklorrvIXuhB1nE0/view.
What I want to do: When the user clicks on a specific state (district or any specific shape) then the data provided in the tiff file should be visible only for that shape. Basically, I want to clip the data in the GeoTIFF file according to a given shape (assuming I have the shape boundary definitions. Further the projection system of the shape boundaries and the GeoTiff file are the same).
Please suggest any approach using georaster, leaflet, georaster-layer-for-leaflet, or some other library.
Here is the code as of now to show whole tiff data on the map.
Code:
import { useEffect, useRef } from "react";
import proj4 from "proj4";
import { useLeafletContext } from "#react-leaflet/core";
import { useMap } from "react-leaflet";
import parseGeoraster from "georaster";
import GeoRasterLayer from "georaster-layer-for-leaflet";
window.proj4 = proj4;
const GeotiffLayer = ({ url, options }) => {
const geoTiffLayerRef = useRef();
const context = useLeafletContext();
const map = useMap();
useEffect(() => {
const container = context.layerContainer || context.map;
fetch(url)
.then((response) => response.arrayBuffer())
.then((arrayBuffer) => {
console.log(arrayBuffer);
parseGeoraster(arrayBuffer).then((georaster) => {
console.log("georaster:", georaster.values[0][1]);
options.georaster = georaster;
geoTiffLayerRef.current = new GeoRasterLayer(options);
container.addLayer(geoTiffLayerRef.current);
map.fitBounds(geoTiffLayerRef.current.getBounds());
});
});
// return () => {
// container.removeLayer(geoTiffLayerRef.current);
// };
}, [context, url, map, options]);
return null;
};
export default GeotiffLayer;
Output:
Fig 1 illustrates the whole tiff file shown on the map.
Fig 2 illustrates the output after a click on the specific state.
What I want to do: When the user clicks on the specific state then tiff data should be shown only for the selected shape, not for other shapes.
Please suggest any approach using georaster, leaflet, georaster-layer-for-leaflet, or some other library.

AntD's Upload keeps showing failed tooltip but it is uploading successfully

I am using antd's Upload component, its task is to just upload the image and then I grab that image and send it to the API to store it. But I keep getting upload failed message tooltip as I am not using any action prop that they provide. Even their own website has this problem as I'm trying to upload something and it shows failed message but it has been actually uploaded. antd's Upload
I am using useState to save the file const [uploadedImage, setUploadedImage] = useState();
My fileProps looks like this:
const fileProps = {
name: 'file',
multiple: false,
onChange(info) {
if (info.file.status !== 'uploading') {
let reader = new FileReader();
reader.onload = (e) => {
setData({
...data,
image: new File([e.target.result], info.file.name),
});
setIsFileUploaded(true);
}
reader.readAsDataURL(info.file.originFileObj);
setUploadedImage(info.file.originFileObj);
}
},
};
I then pass it to the Upload Component:
<Upload {...fileProps}>
<Button icon={<UploadOutlined />}>Upload Image</Button>
</Upload>
Why does it keep showing Upload error Tooltip even though it is successfully uploading and I can store it? how can I remove this tooltip? I know there is a way to hide the list entirely by using: showUploadList: false but I want to show the uploaded file as sometimes during big uploads I don't have any sort of confirmation if the file is uploading or uploaded.
I have also created codesandbox for it: https://codesandbox.io/s/bold-bash-g3qkj
If you just want to save the file to the state, and not send it automatically to the server, you must set the property beforeUpload.
const fileProps = {
name: "file",
multiple: false,
beforeUpload: () => {
return false;
},
onChange(info) {
if (info.file.status !== "uploading") {
let reader = new FileReader();
reader.readAsDataURL(info.file);
setUploadedImage(info.file);
}
}
};

Add name in pdf from text input inside pdf react js

I have a pdf file url (which has a text input in it), which i need to show to user fill his name and submit. I am using pdf-lib to add text field in backend.
In frontend i am using pdf-lib to show pdf file,
Query
I have a text field, which i filled with dummy value, one man punch, when in frontend i change the value and click submit, i am still getting the same value, it's not changing t0 the new value.
Code to load Pdf file from url
const existingPdfBytes = await fetch(url, {
// mode: 'no-cors'
}).then(res => res.arrayBuffer());
const pdfDoc = await PDFDocument.load(existingPdfBytes);
setCurrentPdf(await pdfDoc.saveAsBase64({ dataUri: true }))
Code to show pdf inside iframe
<iframe ref={docRef} style={{width: '100%', height: '35rem'}} title="test-frame" src={currentPdf} type="application/pdf" />
<Button variant='contained' color="primary" onClick={submitClick}>
Submit
</Button>
Code to get File after user enter his name and click submit
const pdfDoc = await PDFDocument.load(docRef.current.src);
// await pdfDoc.save();
const form = pdfDoc.getForm()
const fields = form.getFields()
fields.forEach(field => {
console.log('Signature Value => ',field.getText())
const type = field.constructor.name
const name = field.getName()
// console.log(`${type}: ${name}`)
})
Here is the picture of rendered pdf

How to show uploaded files using initialFiles on material-ui-dropzone?

I am using reactjs and trying to show my uploaded files in preview area of material-ui-dropzone.
First I fetch my uploaded files (just their name) from server and then set it into state. I set initialFiles={uploadedFiles} but my uploaded files not show in preview area. How can I fix that?
My code:
import { DropzoneArea } from "material-ui-dropzone";
export function UploadedFileDropzone(props) {
const [uploadedFiles, setUploadedFiles] = useState([]);
function getUploadedFiles() {
// const files = fetch file names from server
setUploadedFiles(files);
}
useEffect(() => {
getUploadedFile();
}, []);
return (
<div>
<DropzoneArea initialFiles={uploadedFiles}/>
</div>
)
}
Here is what I had and what I expect
There is a property of "DropzoneArea" called 'useChipsForPreview' by default it's false set it to true you will get the desire output

Resources