React-dropzone new reader onload slowly working - javascript

When I request api, I want to make conditional according to the answer, but it doesn't assign the value I want to errorMessageUploaded. Do you have an idea?
I want to get a message when the error comes from api, but when the response comes errormessageupload variable without ending the request.
Not working conditional.
let uploadLoading = false;
let errorMessageUploaded = null;
`function Previews(props) {
const [files, setFiles] = useState([]);
const [test, testFile] = useState(null);
const { getRootProps, getInputProps } = useDropzone({
noClick: props.uploadDisable,
accept: "application/vnd.ms-excel,
application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet",
onDrop: acceptedFiles => {
uploadLoading = true;
var file = acceptedFiles[0];
fileName = file.path;
const reader = new FileReader();
let data = {
file: null,
purchase_order_id: props.purchaseorderid
};
reader.onload = event => {
uploadLoading = true;
data.file = event.target.result.replace(
"data:application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet;base64,",
""
);
});
(async () =>
await axios
.post(
baseUrl + "v1/purchaseorder/uploadpurchaseorder",
data,
axiosConfig
)
.then(response => {
uploadLoading = false;
errorMessageUploaded = null;
window.location.reload();
})
.catch(error => {
errorMessageUploaded = "test";
uploadLoading = false;
throw error;
}))();
reader.readAsDataURL(file);
}
});
const thumbs = files.map(file => (
<FontAwesomeIcon icon={faFileExcel}
className="excelUploadThumbs" />
));
useEffect(
() => () => {
// Make sure to revoke the data uris to avoid memory leaks
files.forEach(file => URL.revokeObjectURL(file.preview));
},
[files]
);
return uploadLoading == false ? (
<section className="container">
<div {...getRootProps({ className: "dropzone" })}>
<input {...getInputProps()} />
<p className="dropzoneText1">Drop your file here</p>
<p className="dropzoneText2">or</p>
<p className="dropzoneText3">Select file</p>
</div>
<aside style={thumbsContainer}>{thumbs}</aside>
</section>
) : errorMessageUploaded != null ? (
<section className="container">
<div className="displayErrorDiv">
<p className="serviceError"> {errorMessageUploaded} </p>
</div>
</section>
) : (
<section className="container">
Data is uploading...
<aside style={thumbsContainer}>{thumbs}</aside>
</section>
);
}`

Code unclear but these may be helpful.
use uploadLoading & errorMessageUploaded with useState
need cancelToken
let source = Axios.CancelToken.source();
const Send = async (url, method, data) => {
try {
source && source.cancel("Operation canceled due to new request.");
source = Axios.CancelToken.source();
return await Axios({ method, url, data, cancelToken: source.token });
} catch (error) {
if (Axios.isCancel(error)) {
return Promise.resolve("canceled");
} else {
return Promise.reject(error);
}
}
};

Related

How do I display a blob octet stream in React? Pinged server, made blob url but doesn't display in SRC of image?

I am trying to display an image on a profile of a user. I have been able to fetch the blob from the API and convert it to a URL blob but when I am trying to return it from the function and into the SRC of the tag, nothing is being displayed.
Previously I was simply displaying the image with <src = ""> and the src that I have put in the function, but when I implemented authentication, this no longer worked because there was a 401 unauthenticated error since no bearer token was sent with the request.
Output:
//profile.js
export const Profile = () => {
const [userProfileInformation, setUserProfileInformation] = useState([]);
const [isLoading, setLoading] = useState(true);
const { userId } = useParams();
useEffect(() => {
getUserProfileInformation().then(() => {
setLoading(false);
});
}, []);
const getUserProfileInformation = async () => {
const response = await UserService.getUserProfileInformation(userId)
.then(response => response.json())
.then(data => {
setUserProfileInformation(data);
});
}
const getProfileImage = async () => {
const src = config.URL + "/users/" + userProfileInformation.userId + "/image/download";
const options = {
headers: {
"Authorization" : `Bearer
${AuthService.getCurrentlyAuthenticatedUser().accessToken}`,
}
};
fetch(src, options)
.then(res => res.blob())
.then(blob => {
console.log(blob);
let url = URL.createObjectURL(blob);
console.log(url);
return url;
});
}
if (isLoading) {
return (
<div id="loading">
<h2>Loading...</h2>
</div>
)
}
return (
<div>
<AppNavbar />
<div className="profileCard">
<img id="profileImg" src={getProfileImage()}/>
<h1>{getFullName(userProfileInformation.firstName, userProfileInformation.lastName)}</h1>
<h2 id="email" role="email">{userProfileInformation.email}</h2>
<h2>{userProfileInformation.location}</h2>
)
}
Any help would be appreciated, thanks.

400 Bad request MP4 (Express, Node, React,mongoDB )

I am trying to stream a mp4 file that is on my computer. I am able to upload and delete the files. When the upload completes and click the link. it routes me to the page and I only see {}. and I get the following errors:
GET http://localhost:8000/read/c94e2bfe215bb8821c5c8dc22c8dc1b4.mp4 400 (Bad Request)
favicon.ico:1 GET http://localhost:8000/favicon.ico 404 (Not Found)
I even uploaded a picture to see to check if the mp4 file was too big, but the picture did not load as well.
Here is my code for my server:
// route for streaming a file
app.get('/read/:filename',async(req,res)=>{
const{filename}= req.params
try{
const readstream = await gfs.createReadStream({filename})
res.header("Content-Type","video/mp4");
res.header("X-Content-Type-Options", "nosniff");
res.header("Accept-Ranges", "bytes");
res.header("Content-Length",903746);
readstream.pipe(res)
}catch(err){
res.status(400).send(err)
}
})
Here is the code for react
function App() {
const [file, setFile] = React.useState(null);
const [files, setFiles] = React.useState([]);
const filehandler = (e) => {
if (e.target.files != null || e.target.files[0] != null) {
setFile(e.target.files[0]);
}
};
const uploadFile = async (e) => {
e.preventDefault();
if (file) {
const fd = new FormData();
fd.append("file", file);
const res = await axios.post("http://localhost:8000/upload", fd);
setFiles(files.concat(res.data))
}
};
const fetchFiles = React.useCallback(async () => {
const res = await axios.get("http://localhost:8000/files");
setFiles(res.data);
}, []);
const removeFile = React.useCallback(
async (filename, index) => {
const res = await axios.delete(
`http://localhost:8000/delete/${filename}`
);
if (res.status === 200) {
let temp = [...files];
console.log(temp);
temp.splice(index, 1);
setFiles(temp);
}
},
[files]
);
React.useEffect(() => {
fetchFiles();
}, [fetchFiles]);
return (
<div className="App">
<form className="Form" onSubmit={uploadFile}>
<input type="file" onChange={filehandler} />
<button type="submit">upload</button>
</form>
<div className="Media">
{files.map((file, i) => (
<div key={file._id} className="Item">
<a
className="Link"
href={`http://localhost:8000/read/${file.filename}`}
>
{file.filename}
</a>
<button
type="button"
onClick={() => {
removeFile(file.filename, i);
}}
>
remove
</button>
</div>
))}
</div>
</div>
);}
Your router is sending 400 after catching an exception. Print exception message using console.log(err) in your catch block to determine what exactly goes wrong it try block's code

Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'hash')

I am trying to make a solution to store the file in IPFS , and then put the hash on the blockchain.
But when I try to upload the file to IPFS here comes the error message
Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'hash')
I am using react , ganache , node.js , ipfs-http-client
here's my app.js code
import React, {Component} from 'react'
import SimpleStorageContract from '../src/SimpleStorage.json'
import getWeb3 from './utils/getWeb3'
import './css/oswald.css'
import './css/open-sans.css'
import './css/pure-min.css'
import './App.css'
const ipfsAPI = require('ipfs-http-client');
const ipfs = ipfsAPI.create({host: 'localhost', port: '5001', protocol: 'http'});
const contract = require('truffle-contract')
const simpleStorage = contract(SimpleStorageContract)
let account;
// Declaring this for later so we can chain functions on SimpleStorage.
let contractInstance;
let saveImageOnIpfs = (reader) => {
return new Promise(function(resolve, reject) {
const buffer = Buffer.from(reader.result);
ipfs.add(buffer).then((response) => {
console.log(response)
resolve(response[0].hash);
}).catch((err) => {
console.error(err)
reject(err);
})
})
}
class App extends Component {
constructor(props) {
super(props)
this.state = {
blockChainHash: null,
web3: null,
address: null,
imgHash: null,
isWriteSuccess: false
}
}
componentWillMount() {
ipfs.swarm.peers(function(err, res) {
if (err) {
console.error(err);
} else {
// var numPeers = res.Peers === null ? 0 : res.Peers.length;
// console.log("IPFS - connected to " + numPeers + " peers");
console.log(res);
}
});
getWeb3.then(results => {
this.setState({web3: results.web3})
// Instantiate contract once web3 provided.
this.instantiateContract()
}).catch(() => {
console.log('Error finding web3.')
})
}
instantiateContract = () => {
simpleStorage.setProvider(this.state.web3.currentProvider);
this.state.web3.eth.getAccounts((error, accounts) => {
account = accounts[0];
simpleStorage.at('0xe7D98C99d71438A072B020138dD75347792FA214').then((contract) => {
console.log(contract.address);
contractInstance = contract;
this.setState({address: contractInstance.address});
return;
});
})
}
render() {
return (<div className="App">
{
this.state.address
? <h1>CONNECT THE CONTRACT ADDRESS:{this.state.address}</h1>
: <div/>
}
<h2>UPLOAD TO IPFS:</h2>
<div>
<label id="file">CLICK TO UPLOAD THE FILE</label>
<input type="file" ref="file" id="file" name="file" multiple="multiple"/>
</div>
<div>
<button onClick={() => {
var file = this.refs.file.files[0];
var reader = new FileReader();
// reader.readAsDataURL(file);
reader.readAsArrayBuffer(file)
reader.onloadend = function(e) {
console.log(reader);
saveImageOnIpfs(reader).then((hash) => {
console.log(hash);
this.setState({imgHash: hash})
});
}.bind(this);
}}>UPLOAD TO IPFS AND RETURN THE HASH</button>
</div>
{
this.state.imgHash
? <div>
<h2>imgHash:{this.state.imgHash}</h2>
<button onClick={() => {
contractInstance.set(this.state.imgHash, {from: account}).then(() => {
console.log('HASH HAS BEEN WRITE ON BLOCKCHAIN');
this.setState({isWriteSuccess: true});
})
}}>PUT HASH ON BLOCKCHAIN:contractInstance.set(imgHash)</button>
</div>
: <div/>
}
{
this.state.isWriteSuccess
? <div>
<h1>HASH IS ON THE BLOCK CHAIN</h1>
<button onClick={() => {
contractInstance.get({from: account}).then((data) => {
console.log(data);
this.setState({blockChainHash: data});
})
}}>READ HASH ON BLOCKCHAIN:contractInstance.get()</button>
</div>
: <div/>
}
{
this.state.blockChainHash
? <div>
<h3>READ THE HASH ON BLOCKCHAIN:{this.state.blockChainHash}</h3>
</div>
: <div/>
}
{
this.state.blockChainHash
? <div>
<h2>BROWSER ACCESS:{"http://localhost:8080/ipfs/" + this.state.imgHash}</h2>
<img alt="" style={{
width: 1600
}} src={"http://localhost:8080/ipfs/" + this.state.imgHash}/>
</div>
: <img alt=""/>
}
</div>);
}
}
export default App
i hope someone can be my savior , thank you really much.
It looks like you're assuming that the response will always be defined. Please check response[0] to see if the response is valid. It looks like onloadend is called asynchronously. Try onload to ensure you're passing information synchronously.
let saveImageOnIpfs = (reader) => {
return new Promise(function(resolve, reject) {
const buffer = Buffer.from(reader.result);
ipfs.add(buffer).then((response) => {
console.log(response)
if(response[0] !== undefined && response[0].hash !== undefined){
resolve(response[0].hash);
}else{
console.log(response)
}
}).catch((err) => {
console.error(err)
reject(err);
})
})
}
At last , my answer has been solved
let saveImageOnIpfs= (reader) => {
return new Promise(async(resolve, reject) => {
try {
const buffer = Buffer.from(reader.result);
let results = await ipfs.add(buffer);
let hash1 = results.path;
resolve(hash1);
} catch (err) {
console.error(err);
reject(err);
}
})
}
thank you for your answer to help me.

Javascript react safe image in database

I have a problem with saving pictures in the database. I want to do a post Method, where i can safe a file in a directory and save the picture link in the database.
Here is my Code:
`const toBase64 = file => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => resolve(reader.result)
reader.onerror = error => reject(error)
})`
` const [base64Image, setBase64Image] = useState("")
const [imagePath, setImagePath] = useState("")
const fileInput = useRef(null)`
`const onFileInputChange = async (e) => {
const file = fileInput.current.files[0]
if (!file) return
const base64 = await toBase64(file)
setBase64Image(base64)}`
` const handleSubmitImage = async (e) => {
e.preventDefault()
if (!base64Image) return
const response = await fetch("/public", {
method: "POST",
headers: {
"content-type": "application/json"
},
body: JSON.stringify(base64Image)
})
const data = await response.json()
setImagePath(data.filePath)
}`
Post:
`const handleSubmit = async (e) => {
e.preventDefault()
setIsLoading(true)
setErrors(defaultModel)
const result = validateModel(post)
if (!result.isValid) {
setErrors(result.errors)
setIsLoading(false)
return
}
if (post.id) {
await updatePost(post, session.accessToken)
alert("Post updated!")
router.push(`/posts/${post.id}`)
} else {
const newPost = await createPost(post, session.accessToken)
alert("Post created!")
router.push(`/posts/${newPost.id}`)
}
setIsLoading(false)
}
`
` <fieldset onSubmit={handleSubmitImage} className={styles.form}>
<p>Image:</p>
<input value={post.image}
type="file"
accept=".png,.jpg"
ref={fileInput}
onChange={onFileInputChange}
/>
{/* eslint-disable-next-line #next/next/no-img-element */}
{base64Image && <img src={base64Image} style={{width: "1000px", height: "1000px"}} alt={""}/>}
{imagePath && <p>
<Link href={`http://localhost:3000${imagePath}`}
passHref><a>http://localhost:3000{imagePath}</a></Link>
</p>
}
</fieldset>`
Right now i can connect to the Explorer and pick an Image. I can also display the image. If i press on create, it doesnt work properly with saving the image in the database.

TypeError: n.map is not a function

I am trying to return the data from this fetch in some cards in another component, but I get the following error:
TypeError: n.map is not a function.
I guess it's because of the async/await, but I don't know how to fix it.
Thanks a lot
export default function Container(){
const [flights, getNewFlights] = useState({});
const user = sessionStorage.getItem("username");
const tipouser = sessionStorage.getItem("TipoUser");
const APT = sessionStorage.getItem("Base");
const Fecha = sessionStorage.getItem("Fecha");
const fetchFlights = async () => {
try {
const flightsData = await $.ajax({
url: "https://listVuelos.php",
type: 'POST',
data: {
APT,
Fecha
}
})
getNewFlights(JSON.parse(flightsData))
} catch (err) {
console.log("Da error")
}
};
useEffect(() => {
fetchFlights()
const interval = setInterval(() => {
fetchFlights()
}, 100000)
return () => interval
}, []);
return(
<Fragment>
<div className="div_container">
{ flights?.map ( f => <IndexCards data={f}></IndexCards> )}
</div>
</Fragment>
);
}
you can't use map function on an object to overcome the problem you can do something like this:
Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, newValue]))

Categories

Resources