src="" not returning when saving images? - javascript

I am using ckeditor in my net.core project. While saving the datatable, the image I added does not appear, it is registered to the database as
<figure class="image"><img></figure>
and src= does not appear as in lowermost the image. My adapter function is as follows
class MyUploadAdapter
{
constructor(loader) {
// The file loader instance to use during the upload.
this.loader = loader;
this.urls = '/tr/UnitType/DocUploadImage';
}
// Starts the upload process.
upload() {
return this.loader.file.then(file => new Promise((resolve, reject) => {
this._initRequest();
this._initListeners(resolve, reject, file);
this._sendRequest(file);
}));
}
// Aborts the upload process.
abort() {
if (this.xhr) {
this.xhr.abort();
}
}
_initRequest() {
const xhr = this.xhr = new XMLHttpRequest();
xhr.open('POST', this.urls, true);
xhr.responseType = 'json';
}
// Initializes XMLHttpRequest listeners.
_initListeners(resolve, reject, file) {
const xhr = this.xhr;
const loader = this.loader;
const genericErrorText = `Couldn't upload file: ${file.name}.`;
xhr.addEventListener('error', () => reject(genericErrorText));
xhr.addEventListener('abort', () => reject());
xhr.addEventListener('load', () => {
const response = xhr.response;
if (!response || response.error) {
return reject(response && response.error ? response.error.message : genericErrorText);
}
resolve({
default: response.urls
});
});
if (xhr.upload) {
xhr.upload.addEventListener('progress', evt => {
if (evt.lengthComputable) {
loader.uploadTotal = evt.total;
loader.uploaded = evt.loaded;
}
});
}
}
// Prepares the data and sends the request.
_sendRequest(file) {
// Prepare the form data.
const data = new FormData();
data.append('upload', file);
this.xhr.send(data);
}
}
function MyCustomUploadAdapterPlugin(editor) {
editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
return new MyUploadAdapter(loader);
};
}
I want to export this.urly to src. How is it given correctly? Is it possible in this way, if not how should I do it please help
DecoupledEditor
.create(document.querySelector('#p_Ack')
,{
extraPlugins: [MyCustomUploadAdapterPlugin],
elements:
{
img: function (element) {
const img = document.querySelector("img");
img.src = this.url;
}
}
}
)
enter image description here
enter image description here

I solved the problem..
For friends who have the same problem, #KIM-DONGWON answered the solution on https://github.com/ckeditor/ckeditor5/issues/5709.

Related

reading the src of an image file in a form

The problem is when i do no not see the form data in the console. I do not know what is wrong. here is the code:
So I got firstly the nodes and tried to create a function thta reads the file and a function that returns a src that would be stored in the readForm data function
//nodes
const mainContainer = document.getElementById("main");
const postTitleNode = document.getElementById("postTitle");
const postDateNode = document.getElementById("postDate");
const postFileNode = document.getElementById("postFile");
const postContentNode = document.getElementById("postContent");
//image file reader
function readImageFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener("load", () => {
resolve(reader.result);
});
reader.addEventListener("error", () => {
reject(reader.error);
});
reader.readAsDataURL(file);
});
}
//reading the src of the image uploaded
function readFileSrc(elementNode) {
return new Promise((resolve, reject) => {
elementNode.addEventListener("change", async () => {
const file = elementNode.files[0];
if (file.type.startsWith("image/")) {
const dataUrl = await readImageFile(file);
postFileNode.value = dataUrl;
resolve(dataUrl);
} else {
console.error("Selected file is not an image.");
reject("Selected file is not an image.");
}
});
});
}
//clear form data
function clearInputValue() {
postTitleNode.value = "";
postDateNode.value = "";
postFileNode.value = "";
postContentNode.value = "";
}
//get form Data
async function readFormData() {
//values: store the values in an object
const postFile = await readFileSrc(postFileNode);
const formData = {
title: postTitleNode.value,
postDate: postDateNode.value,
postFile: postFile,
postContent: postContentNode.value,
};
console.log(formData);
return formData;
}
//onClick function
async function onClickEvent() {
//read data
await readFormData();
//clear data after clicking
clearInputValue();
}
//buttons
const createPostButton = document.getElementById("modalCreatePostButton");
createPostButton.addEventListener("click", onClickEvent);
what can I do to solve the problem or where is my mistake? why am i not getting any data in the console

How to fix this 'unexpected end of JSON input' bug?

Just started a 'Writing JS for the Web' course with following exercise and code, but getting 'unexpected end of JSON input' message upon completion of the exercise. Any idea what's going wrong? I'm coding in the following Codepen: https://codepen.io/nicolaspatschkowski/pen/GRJBZjy?editors=1111
// Get form elements
const titleInput = document.getElementById('title');
const contentInput = document.getElementById('content');
const submitButton = document.getElementById('submit-button');
const url = 'https://us-central1-open-classrooms-js-for-the-web.cloudfunctions.net/widgets';
// Get DOM elements for showing response
const responseMessage = document.getElementById('response-message');
const responseTitle = document.getElementById('response-title');
const responseId = document.getElementById('response-id');
const responseContent = document.getElementById('response-content');
submitButton.addEventListener('click', ($event) => {
$event.preventDefault();
const post = {
title: titleInput.value,
content: contentInput.value
};
submitFormData(post);
});
function makeRequest(data) {
return new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
request.open('POST', url + '/create-post');
request.onreadystatechange = () => {
if (request.readyState === 4) {
if (request.status === 201) {
resolve(JSON.parse(request.response));
} else {
reject(JSON.parse(request.response));
}
}
};
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify(data));
});
}
async function submitFormData(post) {
try {
const requestPromise = makeRequest(post);
const response = await requestPromise;
responseMessage.textContent = response.message;
responseTitle.textContent = response.post.title;
responseId.textContent = response.post.id;
responseContent.textContent = response.post.content;
} catch (errorResponse) { responseMessage.textContent = errorResponse.error;
}
};

Why does removing a console.log call from this async function cause it to upload a black image?

I've come across some strange behavior recently, and I thought I'd share it with y'all.
I've been working on image uploading for a user profile portion of an application I'm build in React. I had a working system for selecting, cropping/resizing, and uploading an image a user selected, so I started to clean up the code, removing the console.logs everywhere. Well, I was disheartened to find that it no longer worked, uploading a purely black image, so I did the obvious—undo my changes until it works again.
All in all I whittled it down to just one line that changed whether it'd work—one, singular console.log statement. Below, you'll see a couple very similar working and non-working versions. I want to hear why y'all think this happens.
Not Working:
const imageBlob: Blob = (await getCroppedImg(imageElement!, crop)) as Blob;
const { data: { requestImageUpload: { putURL, upload: { id: uploadId } } } } = await requestUpload({
variables: {
filename: selectedImage?.name!,
mimetype: imageBlob.type
}
});
await (new Promise((resolve, reject) => {
var oReq = new XMLHttpRequest();
oReq.open("PUT", putURL, true);
oReq.onload = function (e) {
resolve(null);
};
oReq.onprogress = function (e) {
let percent = (e.loaded / e.total) * 100;
setUploadProgress(percent);
};
oReq.onerror = function (e) {
reject(null);
};
oReq.send(imageBlob);
}))
Working:
const imageBlob: Blob = (await getCroppedImg(imageElement!, crop)) as Blob;
const { data: { requestImageUpload: { putURL, upload: { id: uploadId } } } } = await requestUpload({
variables: {
filename: selectedImage?.name!,
mimetype: imageBlob.type
}
});
console.log(imageBlob)
await (new Promise((resolve, reject) => {
var oReq = new XMLHttpRequest();
oReq.open("PUT", putURL, true);
oReq.onload = function (e) {
resolve(null);
};
oReq.onprogress = function (e) {
let percent = (e.loaded / e.total) * 100;
setUploadProgress(percent);
};
oReq.onerror = function (e) {
reject(null);
};
oReq.send(imageBlob);
}))
Also Working:
let imageBlob: Blob = (await getCroppedImg(imageElement!, crop)) as Blob;
const { data: { requestImageUpload: { putURL, upload: { id: uploadId } } } } = await requestUpload({
variables: {
filename: selectedImage?.name!,
mimetype: imageBlob.type
}
});
await (new Promise((resolve, reject) => {
var oReq = new XMLHttpRequest();
oReq.open("PUT", putURL, true);
oReq.onload = function (e) {
resolve(null);
};
oReq.onprogress = function (e) {
let percent = (e.loaded / e.total) * 100;
setUploadProgress(percent);
};
oReq.onerror = function (e) {
reject(null);
};
oReq.send(imageBlob);
}))
Note in the second: there's a console.log call.
Note in the third: I'm using let instead of const.
There are no errors, and the uploaded image is an actual JPEG with all black pixels and a 72 KB size (this depends on the original image). It also has the same dimensions as the intended image.
Is the blob getting garbage collected while it's still being read from for the upload?

React.js . when i am trying to upload more then 3 image files, using FileReader, only 3 uploaded

the next function is getting file and setting it in state obj (arr: [readerEvent.target.result]).
works fine when uploading one file,
fine with 2 and 3.
when I am trying to upload more then 3 files - only 3 uploaded .
I can see that the full (5) list of files is coming into the func by using console.log.
input:
<Input
onChange={handleChange}
type="file"
// accept="image/png, image/jpeg"
multiple
/>
----------------------------------------
Component:
const list = Object.keys(e.target.files).map((elm) => e.target.files[elm]);
list.map((file, index) => {
loadFile(file, index, setImagesList);
});
---------------------------------------------------------------------------------------
Util:
export default function loadFile(file, index, setImagesList) {
// console.log("another file ", file);
let image = new Image();
var reader = new FileReader();
reader.onloadend = function (readerEvent) {
image.src = readerEvent.target.result;
image.onload = function () {
setImagesList((old) => [
...old,
{
key: `${Date.now()}-${file.name}-${index}`,
arr: [readerEvent.target.result],
imageOriginalWidth: image.width,
imageOriginalHeight: image.height,
},
]);
};
};
reader.onerror = function (event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsDataURL(file);
}
OK
found a solution so I will share it.
sending to the util function the entire list and handle it there.
in util func I will update a state that will be the optional loaded file .
only after a check I will set the "real" images list - that will happen out of the util - inside the component:
useEffect(()=>{
uploaded.map((obj, index) => {
if (isValid) {
setImagesList((old) => [...old, obj]);
}
},[uploaded])
-----------------------------------
util :
export default function loadFiles(files, setUploaded) {
const reader = new FileReader();
let arr = [];
function readFile(index) {
if (index >= files.length || index > 5) {
setUploaded(arr);
return;
}
const file = files[index];
reader.onload = function (e) {
let image = new Image();
image.src = e.target.result;
image.onload = function () {
arr.push({
key: `${Date.now()}-${file.name}-${index}`,
name: file.name,
arr: [e.target.result],
imageOriginalWidth: image?.width,
imageOriginalHeight: image?.height,
});
readFile(index + 1);
};
};
reader.readAsDataURL(file);
}
readFile(0);
}
good luck!

how to make a xlxs file as a blob

I am trying to load a xlsx file by clicking a button without using input . The file "seedFile" is inside my project structure .The logic ran correct when I used a input but for internal files I am facing this issue and getting an err.
var excelToJson =function (file) {
return new Promise(function (resolve, reject) {
var xlData = {};
var reader = new FileReader();
reader.readAsBinaryString(seedFile);
reader.onload = function (e) {
var data = e.target.result;
var workbook = XLSX.read(data, {
type: 'binary'
});
workbook.SheetNames.forEach(function (sheetName) {
xlData[sheetName] =
XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
})
};
reader.onprogress = function (data) {
if (data.lengthComputable) {
var progress = parseInt(((data.loaded / data.total) * 100), 10);
console.log(progress);
}
}
reader.onerror = function (ex) {
reject(ex);
};
reader.onloadend = function () {
resolve(xlData)
}
})
}
var handleFiles = function (files) {
var file = seedFile
return excelToJson(file)
}
$("#seedFile").click(async () => {
handleFiles(this.files).then(function success(data) {
console.log(data);
grid.setData(data.Sheet1).getInstance().loadData()
}, function error(err) {
alerts.error(err);
})
})
TypeError: Failed to execute 'readAsBinaryString' on 'FileReader': parameter 1 is not of type 'Blob'. Is there any easy way to make the file as a blob internally ?

Categories