Draft-Js not showing my image using an image URL - javascript

So, I am currently trying to be able to make it possible to paste an image following this [tutorial][1]. The issue I'm having is that I have my code exactly like this tutorial and every time I paste an image it just acts like there was a line break two times with no text. My handlePastedFiles function runs and returns the URL, and then my insertImage runs and passes the link to the insertImage function.
Also, the image url is from a cloud storage and the URL works when viewing in browser.
Here is my handlePastedFiles function:
const handlePastedFiles = (files) => {
console.log('handlePastedFiles is running')
const formData = new FormData();
formData.append('file', files[0])
console.log(files)
fetch(url,
{method: 'POST', body: formData})
.then(res => {
return res.json()
})
.then(data => {
console.log(data)
if (data.message) {
console.log(data.message)
setEditorState(insertImage(data.message)) //created below
} else {
console.log('no file found')
}
}).catch(err => {
console.log(err)
})
}
and here's my insertImages function:
const insertImage = ( url) => {
console.log('!!!!!', url)
const contentState = editorState.getCurrentContent();
const contentStateWithEntity = contentState.createEntity(
'IMAGE',
'IMMUTABLE',
{ src: url },)
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
const newEditorState = EditorState.set( editorState, { currentContent: contentStateWithEntity });
return AtomicBlockUtils.insertAtomicBlock(newEditorState, entityKey, ' ');
};
Please any help is much appreciated, and let me know if I need more information. Thank you in advance!
[1]: https://daveteu.medium.com/draftjs-insert-paste-images-into-your-content-820159025258

Related

How to convert SVG to PNG or JPG/JPEG files in React.js

How can I convert SVG files to png,jpg or jpeg Files in React.js Because I am trying to send my files to server and server only accepts jpg/jpeg or png. Any help? I only need files in one of these types. I don't need them in url or blob.
The screenshot of file in console
I searched all over the place. There are some but either the solution is for backend or javascript with dom
const [fileImages, setFileImages] = useState<File[]>([]);
const { state } = useAssetReportContext();
const charts = state.chartsList.map(({ url, fileName }) => ({
url,
fileName,
}));
useEffect(() => {
const fetchImages = () => {
charts.map(({ url, fileName }) => {
fetch(url)
.then((response) => response.blob())
.then(
(blob) =>
new File([blob], `${fileName}`, {
type: blob.type,
})
)
.then((file) => {
setFileImages((prev) => [...prev, file]);
});
});
};
fetchImages();
}, [state.chartsList.length]);
You can use 'convert-svg-to-png' library.
This is the npm link
Then import it:
const { convertFile } = require('convert-svg-to-png');
Then use the following code:
(async() => {
const inputFilePath = '/path/to/my-image.svg';
const outputFilePath = await convertFile(inputFilePath);
console.log(outputFilePath);
//=> "/path/to/my-image.png"
})();
Hope it works for you :)

Web Share API - link and text does not appear on social media

I want to use web share api, so i can share specific image coming from google spreadsheet with text and description, but unfortunatelly only image is being shared to facebook. The text, title and url it's missing. For whatsapp if working fine for example. Can anyone give hand for this? Thanks
Code below:
`
async function share() {
const imageQuote = '<?=$image_quote; ?>';
const response = await fetch(imageQuote);
const blob = await response.blob();
let pageTitle = 'THe Page';
let pageText = document.getElementsByClassName("quote")[0].innerText;
let pageUrl = window.location.href;
const filesArray = [
new File(
[blob],
'panion.jpg',
{
type: blob.type,
lastModified: new Date().getTime()
}
)
];
const shareData = {
title: pageTitle,
text: pageText,
url: pageUrl,
files: filesArray,
};
if (navigator.share) {
navigator
.share(shareData)
.then(() => console.log("Successful share"))
.catch((error) => console.log("Error sharing", error));
} else {
console.error("Browser doesn't support Web Share API");
}
console.log(shareData);
}
function shareThisQuote() {
return share();
}
`

Text -> PNG -> ReadStream, all done on the front-end?

I'm not sure if this is even possible, but here's what I'm trying to do:
Let the user enter some text
Generate a PNG from that text
Upload it to Pinata, which requires it to be in ReadStream format
Do all of this on the front-end
I've managed to accomplish (1) and (2) using html2canvas.
The tricky part is (3). The reason it has to be in ReadStream format is because that's the format Pinata's SDK wants:
const fs = require('fs');
const readableStreamForFile = fs.createReadStream('./yourfile.png');
const options = {
pinataMetadata: {
name: MyCustomName,
keyvalues: {
customKey: 'customValue',
customKey2: 'customValue2'
}
},
pinataOptions: {
cidVersion: 0
}
};
pinata.pinFileToIPFS(readableStreamForFile, options).then((result) => {
//handle results here
console.log(result);
}).catch((err) => {
//handle error here
console.log(err);
});
I realize that this would be no problem to do on the backend with node, but I'd like to do it on the front-end. Is that at all possible? Or am I crazy?
I'm specifically using Vue if that matters.
For anyone interested the solution ended up being using fetch+blob:
const generateImg = async () => {
const canvas = await html2canvas(document.getElementById('hello'));
const img = canvas.toDataURL('image/png');
const res = await fetch(img);
return res.blob();
};
This blob can then be passed into a more manual version of their SDK:
const uploadImg = (blob: Blob) => {
const url = `https://api.pinata.cloud/pinning/pinFileToIPFS`;
const data = new FormData();
data.append('file', blob);
const metadata = JSON.stringify({
name: 'testname',
});
data.append('pinataMetadata', metadata);
const pinataOptions = JSON.stringify({
cidVersion: 0,
});
data.append('pinataOptions', pinataOptions);
return axios
.post(url, data, {
maxBodyLength: 'Infinity' as any, // this is needed to prevent axios from erroring out with large files
headers: {
// #ts-ignore
'Content-Type': `multipart/form-data; boundary=${data._boundary}`,
pinata_api_key: apiKey,
pinata_secret_api_key: apiSecret,
},
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
};

react-media-recorder not Stopping recording in deployment

I am using react-media-recorder to record audio. It works fine on localhost but when deployed to a server and accessed, the onStop method stops working. It doesn't get invoked.
this is my file:
import { useReactMediaRecorder } from "react-media-recorder"
const { status, startRecording, stopRecording, error, mediaBlobUrl, clearBlobUrl } = useReactMediaRecorder({
audio: true,
type: "audio/wav",
onStop: (blobUrl, blob) => {
console.log("onStop recording")
const url = URL.createObjectURL(blob)
let formData = new FormData()
//person_name-person_id-language_id-sentence.id-date
const today = new Date()
// const file_name = `${id}-${language_id}-${sentence.id}-${today.toISOString()}.wav`
const file_name = `${name}-${id}-${language_id}-${
sentence.id
}-${today.toDateString()}-${language_name}.wav`
console.log("-------------------------------------------------------")
console.log("file_name :>>", file_name)
console.log("-------------------------------------------------------")
formData.append("file", blob, file_name)
let upload_url
if (sample) {
upload_url = "sentence/upload_audio_sample"
} else {
upload_url = "sentence/upload_audio"
}
console.log(`upload_url`, upload_url)
axios
.post(upload_url, formData)
.then((d) => console.log("after post blob :>>", d))
.catch((e) => console.log("error in post blob :>>", e))
},
})
const handleStartRecording = () => {
setRecording(!recording)
if (!recording) {
clearBlobUrl()
startRecording()
} else {
stopRecording()
}
}
any help is much appreciated
for this to work both the frontend and backend need to be on https.
Make sure your backend server is running on https

How to make direct api call to cloudinary with axios?

I am trying to figure this out with axios. I have made the direct api call with superagent and now want to know how to use with axios as the rest of my project is with axios. I know there is cloudinary-react, but this is the way I prefer to do it.
Here is what I have so far.
import React, { Component } from 'react';
import Dropzone from 'react-dropzone';
import sha1 from 'sha1';
import superagent from 'superagent';
import axios from 'axios';
class Images extends Component {
uploadFile(files) {
console.log('uploadFile: ');
const image = files[0];
const cloudName = 'tbaustin';
const url = `https://api.cloudinary.com/v1_1/${cloudName}/image/upload`;
const timestamp = Date.now()/1000;
const uploadPreset = 'cnh7rzwp';
const paramsStr = `timestamp=${timestamp}&upload_preset=${uploadPreset}secret`;
const signature = sha1(paramsStr);
const params = {
'api_key': 'api_key',
'timestamp': timestamp,
'upload_preset': uploadPreset,
'signature': signature
}
let uploadRequest = superagent.post(url)
uploadRequest.attach('file', image);
Object.keys(params).forEach((key) => {
uploadRequest.field(key, params[key]);
});
uploadRequest.end((err, res) => {
if(err) {
alert(err);
return
}
console.log('UPLOAD COMLETE: '+JSON.stringify(res.body));
});
//AXIOS CONTENT HERE
// let request = axios.post(url, {file: image});
// request.then((response) => {
// Object.keys(params).forEach((key) => {
// uploadRequest.field(key, params[key]);
// });
// console.log('UPLOAD COMPLETE: '+JSON.stringify(response.body));
// }).catch((err) => { alert(err); });
}
render() {
return (
<div>
<Dropzone onDrop={this.uploadFile.bind(this)}/>
</div>
)
}
}
export default Images;
This worked for me.
let formData = new FormData();
formData.append("api_key",'');
formData.append("file", image);
formData.append("public_id", "sample_image");
formData.append("timestamp", timeStamp);
formData.append("upload_preset", uploadPreset);
axios
.post(url, formData)
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
})
This is a part of my project when I tried to upload an avatar. I have set my upload preset to unsigned on cloudinary.
const uploadPhotoHandler = async (e) => {
const file = e.target.files[0];
const formData = new FormData();
formData.append("file", file);
formData.append("upload_preset", "pa*****");
try {
setPictureProfile("./assets/img/giphy.gif");
const res = await axios.post("https://api.cloudinary.com/v1_1/${cloud_name}/upload", formData);
console.log(res.data.url);
setPictureProfile(res.data.url);
} catch (error) {}
};

Categories

Resources