How can we add react js pdf file in firebase realtime database - reactjs

I am trying to add reactjs pdf file in real time database but my file is not added in firebase. I am shared my code please anyone can help me to solve this issue
my code
import React, { useState } from 'react'
function Demo() {
const [file, setFile] = React.useState("");
function handleUpload(event) {
setFile(event.target.files[0]);
}
const postData = async (e) => {
e.preventDefault();
const result = await fetch('------/data.json', {
method: "POST",
headers: {
"Content-Type": "application/json",
}, body: JSON.stringify({
file
})
})
if (result) {
setFile({file:''})
alert("message send successfull...")
}
} else {
alert("please fill data")
}
}
)
return (
<div>
<div id="upload-box">
<input type="file" onChange={handleUpload} />
<p>Filename: {file.name}</p>
</div>
<button type="button" onClick={postData} className="btn btn-warning" > Submit feedback </button>
</div>
)

Related

Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob' ReactJS

Guys why does it show me this error when I try to upload a PDF file "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'":
function Test() {
const [file, setFile] = useState()
const SubmitFile = (e) =>{
e.preventDefault()
const formdata = new FormData()
try {
formdata.append(
'file',
file,
file.name,
)
axios.post("http://localhost:3001/upload", formdata,{
headers:{
"Content-type": "multipart/form-data"
},
})
} catch (err) {
console.log(err.message)
}
}
return (
<div>
<h1>File upload</h1>
<form onSubmit={SubmitFile}>
<input onChange={(e)=>{setFile(e.target.files)}} accept="application/pdf" type=
{"file"} id='file' />
<input type={"submit"} value="submit" />
</form>
</div>
)
}
export default Test
I just had to change into this:
let formdata = new FormData()
try {
formdata.append(
'file',
file[0],
file.name,
)

How to upload image to specific collection with reactjs?

I am trying to upload an image to specific collection and wrote a function to send post request to nodejs server but it is not working properly. Well when i upload by postman it is working fine but the logic that i wrote in front end seems not working. Here is the code :
const [image, setImage] = useState(null);
const [isCollectionCreated, setIsCollectionCreated] = useState(false);
const postImage= async () => {
const data = await response.json()
if (image) {
const fd = new FormData();
console.log("FD",fd);
fd.append("image", image);
await fetch(
`https://itransition-capstone.herokuapp.com/collections/${data._id}`,
{
method: "POST",
body: fd,
headers: {
"Authorization": "Bearer " + token,
},
}
);
alert("Image uploaded");
}
}
};
return (
<Form>
<Form.Group>
<Form.Label>Upload an image</Form.Label>
<Form.Control
type="file"
alt="file-upload"
value={requestData.image}
onChange={(event) => {
console.log(event.target.files);
setImage(event.target.files[0]);
}}
/>
</Form.Group>
<Button
variant="success"
type="submit"
className="mt-3 rounded-pill"
onClick={postImage}
>
Submit
</Button>
</Form>
)

Can't send files using Redux Form

I'm creating a webpage for me and I'm working with Redux/Redux Form. My backend is working fine, but I can't figure out how to work on my front-end. I'm not using any library to fetch the image in my front, I just copy and pasted a FieldFileInput and it's working fine.
Here is my PostForm.tsx:
renderInput = ({input, label, meta}: {input: any, label: any, meta: any}) => {
const className = `field ${meta.error && meta.touched} ? 'error' : ''`;
return (
<div className={className}>
<label>{label}</label>
<div className="input-group input-group-lg">
<input className="form-control"{...input} autoComplete="off"/>
</div>
{this.renderError(meta)}
</div>
)
};
onSubmit = (formValues: any) => {
//#ts-ignore
this.props.onSubmit(formValues)
};
render() {
return (
<form
onSubmit={ this.props.handleSubmit(this.onSubmit)}
className="ui form error"
>
<div className="create-post-field-two">
<Field
name="title"
component={this.renderInput}
label="Enter Title"
/>
</div>
<div className="create-post-field-two">
<Field
name="body"
component={this.renderInput}
label="Enter Description"
/>
</div>
<div className="create-post-field-two">
<Field
name="imageUrl"
component={FieldFileInput}
label="Enter Image"
/>
</div>
<div className="postButton">
<button className="btn btn-outline-secondary">Submit</button>
</div>
</form>
)
}
}
In this page I'm certain that everything works correctly, because I receive all data in my Action.
Here is my Redux Action
export const createPost = ( formValues: any) => async(dispatch: any, getState: any) => {
const { userId } = getState().auth;
let token = userId
const headers = {
// 'Content-Type': 'multipart/form-data',
authorization: `Bearer ${token}`,
};
let formData = new FormData();
formData.append('imageUrl', formValues.imageUrl);
try {
const response = await AlleSys.post('/posts', {...formValues, image: formData}, {headers})
dispatch({type: CREATE_POST, payload: response.data})
history.push('/')
}catch (err) {
console.log("ERROR: Couldn't post for identified user");
}
};
If I uncomment the Content-Type I receive the error Error: Multipart: Boundary not found
in my Back-End.
Here Is a screenshot of my request using insomnia.
I'm stuck on this for days and I can't figure out how to achieve the file upload in the front-end. Please don't mind the typings, I'll correct later.
I used bodyFormData.append to my form fields in the Redux Action and worked like a charm.
export const createPost = ( formValues: any) => async(dispatch: any, getState: any) => {
const { userId } = getState().auth;
let token = userId
const headers = {
authorization: `Bearer ${token}`,
Accept: 'application/json',
};
const { title, body, image } = formValues;
const bodyFormData = new FormData();
bodyFormData.append('title', title);
bodyFormData.append('body', body);
bodyFormData.append('image', image);
try {
const response = await AlleSys.post('/posts', bodyFormData, {headers})
console.log(response)
dispatch({type: CREATE_POST, payload: response.data})
history.push('/')

Mulitple image add in react js

I am working on a project where I have one page where you should be able to add images. One by one it's worked perfectly. Now I want to make to be able to multiple add and upload. I don't want to use any library for image upload.
const onFileChange = (e) => {
const reader = new FileReader();
reader.onload = () => {
if (reader.readyState === 2) {
setPreview(reader.result);
}
};
reader.readAsDataURL(e.target.files[0]);
if (e.target.files[0]) {
setOver(true);
}
const copy = [...image];
copy.push(e.target.files[0]);
setImage([...copy]);
};
const onFileUpload = () => {
const formdata = new FormData();
image.forEach((elem) => {
formdata.append("data", elem);
});
formdata.append("id_grobnog_mjesta", Id);
addImage(formdata);
};
const addImage = async (data) => {
try {
setIsLoading(true);
const response = await apiRequest({
method: "post",
url: `spisak-srebrenica/upload`,
headers: {
Authorization: `Bearer ${token}`,
},
data,
});
if (response.data.success) {
getVictimImage();
}
setIsLoading(false);
setImage([]);
} catch (err) {
setIsLoading(false);
setImage([]);
}
};
Upload component :
<Upload>
<BiImageAdd size={50} opacity={0.5} />
<input type="file" onChange={onFileChange} />
<div className="items">
<p>Dodajte sliku</p>
<span className="format">PNG,JPG,GIF do 10MB</span>
</div>
</Upload>
add multiple attribute
<input type="file" id="files" name="files" multiple>
https://www.w3schools.com/tags/att_input_multiple.asp

Keep on getting 400 (Bad Request) on a POST request

So I'm trying to make a request to a database I have set up. The point is to send a POST to add to the table and for it to feed my back the full list.
I keep on getting "POST http://localhost:8000/api/folders 400 (Bad Request)" in the console. I know it's the POST as when I check the database on both DBeaver and POSTman the database remains the same.
I tried writing '"name"' as 'name' and that didn't change anything.
const postfolder = {
method: 'POST',
body: JSON.stringify({ "name" : f })
};
const getFolder = {
method: 'GET'
};
fetch(`${config.API_ENDPOINT}/folders`, postfolder)
.then(
fetch(`${config.API_ENDPOINT}/folders`, getFolder)
)
.then(res => {
if (!res.ok)
return res.json().then(e => Promise.reject(e))
})
.then(folders => {
this.setState({folders : folders});
})
.catch( error =>{
console.error({ error });
console.log("I fucked up the coding: 001");
});
EDIT:
For clarity here is the component that defines f. Though I did have a console.log (not seen in above) that checks the value and it's giving me the correct one.
import React, {Component} from 'react';
//import { NavLink, Link } from 'react-router-dom'
import './AddFolder.css';
export default class AddFolder extends Component{
handleSubmit = (e) => {
e.preventDefault();
console.log("handleSubmit ran");
var nameError = document.getElementById("folderNameError");
if (!e.target.name.value){
nameError.classList.remove("hidden");
return console.log("no name");
}
nameError.classList.add("hidden");
return this.props.addNewFolder(e.target.name.value);
// process form values here
}
render(){
return (
<form className="folderForm" onSubmit={(e) => this.handleSubmit(e)}>
<h3>New Folder</h3>
<label>Text </label>
<input type="text" className="elementName" name="name" id="folderName"/>
<div>
<button type="submit" className="registration__button">
Save
</button>
</div>
<div>
<button type="reset" className="registration__button">
Cancel
</button>
</div>
<div className="errorSpace">
<p className="hidden" id="folderNameError">A name is required</p>
</div>
</form>
)
}
}
Here's a quick picture of the database. It's just a name and an id.
I'm able to fetch to it using POSTMAN so I don't believe it's the issue.
So I found out that the issue was that I needed to add to my fetch request.
I had it as:
const postfolder = {
method: 'POST',
body: JSON.stringify({ "name" : f })
};
It should be:
const postfolder = {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(newFolder)
};
I needed the content-type.

Resources