0

I have a posting system for a blog. The issue is when I try to post an image (which was inputed)by using the createElement() function of Javascript it just does not work.

HTML and Js code:

function publish() {
  var title = document.getElementById("title").value;
  var description = document.getElementById("description").value;
  var para = document.createElement("h3");
  var node = document.createTextNode(title);
  para.appendChild(node);

  var element = document.getElementById("posts");
  element.appendChild(para);

  var para = document.createElement("small");
  var node = document.createTextNode("--".concat(description, "--"));
  para.appendChild(node);

  var image = document.getElementById("posts")
  element.appendChild(para)
  var image = document.getElementById("image-file").value
  var para = document.createElement("img");
  var node = document.createTextNode(image);
  para.appendChild(node);
}
<button id="publish-button" onclick="publish()">Publish</button>
<p>Title</p>
<input class="Title" id="title"></input>

<p>Description</p>
<input class="Description" id="description"></input>

<p>Images</p>
<input id="image-file" type="file" />

<h1>The Blog</h1>
<ul id="posts"></ul>
sassy_rog
  • 1,077
  • 12
  • 30

1 Answers1

1

You can use URL.createObjectURL() to solve your issue. Please check the following code.

  var image = document.createElement("img");
  var imageInput = document.getElementById('image-file');
  image.src = URL.createObjectURL(imageInput.files[0]);
  image.style.height = '100px';
  image.style.width = '100px';

  para.appendChild(image);

function loadFile(event) {
  
}


function publish() {
  var title = document.getElementById("title").value;
  var description = document.getElementById("description").value;
  var para = document.createElement("h3");
  var node = document.createTextNode(title);
  para.appendChild(node);

  var element = document.getElementById("posts");
  element.appendChild(para);

  var para = document.createElement("small");
  var node = document.createTextNode("--".concat(description, "--"));
  para.appendChild(node);

  element.appendChild(para)
  
  // Add image
  var image = document.createElement("img");
  var imageInput = document.getElementById('image-file');
  image.src = URL.createObjectURL(imageInput.files[0]);
  image.style.height = '100px';
  image.style.width = '100px';
  
  para.appendChild(image);
}
<button id="publish-button" onclick="publish()">Publish</button>
<p>Title</p>
<input class="Title" id="title"></input>

<p>Description</p>
<input class="Description" id="description"></input>

<p>Images</p>
<input id="image-file" type="file" accept="image/*" />

<h1>The Blog</h1>
<ul id="posts"></ul>
Sifat Haque
  • 5,357
  • 1
  • 16
  • 23