I am trying to use the rich text editor TinyMCE for a blog platform I am currently working on.
I am also using React with a Flask backend. A
User should be able to create a blog entry with the editor and also use/ upload images.
I got everything setup but I don't know how to store the images in my backend so you can save a blog with all it's content.
I got this callback function from their documentation but I do not really understand what's happening there and if it is enough to send the file object to my backend and store it in the database.
file_picker_callback: function (cb, value, meta) {
var input = document.createElement("input");
input.setAttribute("type", "file");
input.setAttribute("accept", "image/png , image/jpg");
input.onchange = function () {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function () {
var id = "blobid" + new Date().getTime();
var blobCache =
window.tinymce.activeEditor.editorUpload.blobCache;
var base64 = reader.result.split(",")[1];
var blobInfo = blobCache.create(id, file, base64);
blobCache.add(blobInfo);
/* call the callback and populate the Title field with the file name */
cb(blobInfo.blobUri(), { title: file.name });
};
reader.readAsDataURL(file);
console.log(file);
};
This is the console.log(file) output
File {name: "wlogLogo.png", lastModified: 1590578382000, webkitRelativePath: "", size: 4591, type: "image/png", …}
Related
I'm new in React and trying to create an Application which can open a local JSON File with a list of elements like this in a dialouge:
{
"autor": "Name",
"selftext": "Text",
"title": "Title",
"date": "2019-11-18 18:36:40",
"content": "Content",
"link": "www.web.com",
"origin": "web.com",
"filename": "XY",
"id": 1
},
The imported JSON should be expandable and editable and after that export it with the changes.
Here I need some help with guidance where to start and what I need for that.
To read the file on the frontend, you will need to:
Construct a <form onSubmit={handleSubmit}> with an <input name='json' type='file' required>
Then create a callback, handleSubmit, that extracts and parses the chosen file:
function handleSubmit(e: Event) {
e.preventDefault(); // Prevents the form from refreshing the page
const formData = new FormData(e.target); // parses the data into a map
const file = formdata.get("json");
const filereader = new FileReader();
filereader.readAsText(file);
filereader.onload = () => handleResult(filereader.result);
}
function handleResult(result: string|ArrayBuffer|null) {
if (result) {
// Handle the file as you would like here. You will likely need to
// parse the file here w/ JSON.parse. You could cache it
// or pass it to the React.Context API so that it is available through
// the application.
}
}
To write/export the file on the frontend, you can push the JSON object into a Blob and temporarily construct an <a> element to initiate the download:
function save() {
const json = // retrieve JSON from wherever you stored it
const file = new Blob([json], {endings: 'native'});
const a = document.createElement('a');
a.download='config.cfg'
a.href = URL.createObjectURL(file);
a.click();
}
Granted because the process might be slightly different because of Electron, but that is how it would work with React in the Browser.
Hey guys I am using NGX Dropzone and I notice when I drag an image into the viewer it is in base64, but when I try to read the console.log(event.addedFiles); I have no information being passed to me with the base64 value. Here's an example of what I get back
[File]
0: File
lastModified: 1625149167659
lastModifiedDate: Thu Jul 01 2021 10:19:27 GMT-0400 (Eastern Daylight Time) {}
name: "210534431_764639924207804_238792847075232344_n.jpeg"
size: 101133
type: "image/jpeg"
webkitRelativePath: ""
__proto__: File
length: 1
__proto__: Array(0)
I have another piece of code which I have been using that transforms a URL into a base64 string. But thats useless to me since the URL can also be shared and opened by anyone from anywhere. However my local image in my computer is only available to me, unless I transform it into base64 which is a string I can save in a database.
This is the script
imageToShow: any;
onURLinserted() {
this.getImage(this.thumb.name).subscribe(data => {
this.createImageFromBlob(data);
}, error => {
console.log("Error occured",error);
});
console.log("Data: ", this.thumb.name);
}
getImage(imageUrl: string): Observable<Blob> {
return this.http
.get<Blob>(imageUrl, { observe: 'body', responseType: 'blob' as 'json' })
}
createImageFromBlob(image: Blob) {
let reader = new FileReader(); //you need file reader for read blob data to base64 image data.
reader.addEventListener("load", () => {
this.imageToShow = reader.result; // here is the result you got from reader which I use to view the image
this.selectedRowData.photo = reader.result; // this is my ngModel read by my HTML input fields
}, false);
if (image) {
reader.readAsDataURL(image);
}
}
//In my HTML code
<img [src]="imageToShow" alt="">
All I am really trying to do is extract the base64 information from the image dragged in there into imageToShow either by using this code if it helps or something similar OR maybe the cdk drag an drop already has a prop that I dont know about
How do I know that the base64 is even available? When I drag an image in it, and I inspect it in the dev tool I can see the src="data:image/jpeg;base64,random stuff..."
Wish I could put some test code here but I will need the dropzone library for it
Looks like ngx-dropzone does not have a prop that provides bas64String.
You can use readAsDataURL to get base64String. The readAsDataURL is used to read the contents of the Blob or File. When the loadend is triggered. At that time, the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string.
The below code worked for me.
html file
<div class="custom-dropzone" ngx-dropzone [accept]="'image/jpeg,image/jpg,image/png,image/gif'"
(change)="onSelect($event)">
<ngx-dropzone-label>
<div>
<h2>Upload photo</h2>
</div>
</ngx-dropzone-label>
<ngx-dropzone-image-preview ngProjectAs="ngx-dropzone-preview" *ngFor="let f of files" [file]="f"
[removable]="true" (removed)="onRemove(f)">
</ngx-dropzone-image-preview>
</div>
.ts file
onSelect(event) {
this.files.push(...event.addedFiles);
if (this.files && this.files[0]) {
for (let i = 0; i < this.files.length; i++) {
this.fileToBase64(this.files[i])
.then(result=>{
const base64String = result.replace('data:', '')
.replace(/^.+,/, ''); // To remove data url part
this.postMultimedias.push({ name:this.files[i].name,content:
base64String});//postMultimedias is a array which holds image name and bas64String
});
}
}
}
fileToBase64 = (file:File):Promise<string> => {
return new Promise<string> ((resolve,reject)=> {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result.toString());
reader.onerror = error => reject(error);
})
}
onRemove(event) {
let position = this.files.indexOf(event);
this.postMultimedias.splice(position, 1);
this.files.splice(position, 1);
}
I'm trying to convert an audio file into a Base64String to upload to a server.
For certain reasons, I want to do this on the phone before I upload this. I'm using React Native inside the Expo kit.
My file structure looks like this:
let uriParts = uri.split('.');
let fileType = uriParts[uriParts.length - 1];
let formData = new FormData();
formData.append('file', {
uri,
name: `file.${fileType}`,
type: `audio/${fileType}`,
});
Assume we have the uri and it's a .wav audio file
I was able to do this conversion with a NodeJS server with multer doing the heavy lifting.
It would give a buffer to the route and then I could convert the buffer to a base64 string and then send it to another server to process the buffer.
Any idea how can get this done on React Native or purely on the frontend?
Thanks!
You can use FileReader class.
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
Or you can send as a blob (It is not base64).
Use https://github.com/wkh237/react-native-fetch-blob library
I am recording an audio through browser and storing it as a blob using react-mic library, I need to change the blob audio file to mp3/ogg/wav file and store it in local directory using ReactJS.
Blob example:
{blob: Blob(5899), startTime: 1518600546820, stopTime: 1518600547833, options: {audioBitsPerSecond :128000, mimeType:"audio/mpeg"},
blobURL: "blob:http://localhost:3000/3ac81ece-237f-4265-8225-6653b2beb0bc"}
Here I am storing a blob in a state,
onStop = (recordedBlob) => {
this.setState({
blobMain: recordedBlob
})
}
instead of a blob I wanted to store a mp3/ogg/wav file. And use the state for api response.
I tried using Filereader() to convert the blob to ArrayBuffer and convert it as a mp3/ogg/wave file.
onStop = (recordedBlob) => {
var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function() {
arrayBuffer = this.result;
};
fileReader.readAsArrayBuffer(recordedBlob);
this.setState({
blobMain: fileReader
})
}
But I get an error as:
TypeError: Failed to execute 'readAsArrayBuffer' on 'FileReader': parameter 1 is not of type 'Blob'.
I'm trying to upload audio file to Firebase Storage in my Ionic2 project.
First I recorded a audio file using Media plugin (Cordova plugin), and this file is playing well. From the Android storage and from the media plugin method (this.media.play()...;).
Second I need to push the recorded file to Firebase Storage.
this is my code:
let storageRef = firebase.storage().ref();
let metadata = {
contentType: 'audio/mp3',
};
let filePath = `${this.file.externalDataDirectory}`+`${this.fileName}`;
const voiceRef = storageRef.child(`voices/${this.fileName}`);
var blob = new Blob([filePath], {type: 'audio/mp3'});
voiceRef.put(blob);
After reading the Firebase doc, I can push blob to Firebase.
The file is successfully pushed to Firebase Storage with empty data (95 Byte).
this is screenshot:
The problem isn't a Firebase issue
My problem is solved by using the File cordova plugin method (readAsDataURL()) and the putString(fileBase64,firebase.storage.StringFormat.DATA_URL) method.
First, I create a file reference:
let filePath = "this.file.externalDataDirectory" + "this.fileName";
Then I transform the file to a base64 string by using the readAsDataURL method that returns a promise containing the file as a string base64. Also, I push the file to Firebase using the putString method that has two parameters the File that returned by the readAsDataURL and the second is firebase.storage.StringFormat.DATA_URL.
My Final code:
let storageRef = firebase.storage().ref();
let metadata = {
contentType: 'audio/mp3',
};
let filePath = `${this.file.externalDataDirectory}` + `${this.fileName}`;
this.file.readAsDataURL(this.file.externalDataDirectory, this.fileName).then((file) => {
let voiceRef = storageRef.child(`voices/${this.fileName}`).putString(file, firebase.storage.StringFormat.DATA_URL);
voiceRef.on(firebase.storage.TaskEvent.STATE_CHANGED, (snapshot) => {
console.log("uploading");
}, (e) => {
reject(e);
console.log(JSON.stringify(e, null, 2));
}, () => {
var downloadURL = voiceRef.snapshot.downloadURL;
resolve(downloadURL);
});
});
That's working fine for me.
Thanks.