Showing Image in django

Tags: , , ,



I have a Django web app where I am uploading an image and showing some texts. But I am not able to show the image in the front end after uploading.

views.py

def index(request):
    if request.method == "GET":
        return render(request, 'index.html')
    elif request.method == "POST":
        input_file = request.FILES['file']
        media_root = settings.MEDIA_ROOT
        fs = FileSystemStorage()
        filename = fs.save(input_file.name, input_file)
        uploaded_file_url = fs.url(filename)
        filepath = os.path.join(media_root, filename)
        images = segment_lines(filepath)
        extracted_text = extract()
        copy2(filepath, '/home/user/ocr/ocr/static/'+ filename)
        response = { "response" : extracted_text, "img": filename}
        return JsonResponse(response, safe=False)

index.html

<form action="" id="file-form" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <div class="row">
        <div class="col-sm-10 col-md-10 col-lg-9">
            <div class="form-group">
               <div class="input-group">
                   <div class="input-group-prepend">
                       <span class="input-group-text" id="inputGroupFileAddon01">Upload</span>
                    </div>
                    <div class="custom-file">
                        <input type="file"  accept="image/*" name="file" class="custom-file-input" id="inputGroupFile01" aria-describedby="inputGroupFileAddon01">
                        <label class="custom-file-label" for="inputGroupFile01">Choose file</label>
                    </div>
                </div>           
            </div>            
      </div>

      <div class="col-sm-2 col-md-2 col-lg-3">
          <span class="upload-btn">
          <button type="submit" id='upload-button' class="btn btn btn-outline-dark">Extract</button>
          </span>
      </div>
     </div>
 </form>
<div class="row" style="border:none;">
      <div class="col-xs-6 mx-auto" id="img_data">
      </div>
      <div class="col-xs-6 mx-auto" id="content_data">
      </div>
</div>
<script type="text/javascript">
    var form = document.getElementById('file-form');
    var fileSelect = document.getElementById('inputGroupFile01');
    var uploadButton = document.getElementById('upload-button');

    form.onsubmit = function(event) {
      event.preventDefault();
      uploadButton.innerHTML = 'Processing ...';
      var file = fileSelect.files[0];
      var formData = new FormData();
      formData.append('file', file, file.name);
      formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');

      var xhr = new XMLHttpRequest();
      xhr.open('POST', 'http://127.0.0.1:8000', true);

      xhr.onload = function () {

        if (xhr.status === 200) {
          uploadButton.innerHTML = 'Extract';
          var data = JSON.parse(xhr.responseText);
          var follow_up = data['response'];
          var corrected = data["correct_response"]
          var demoid = document.getElementById("content_data");

          var btnid = document.getElementById('btn-data')
          var imgid = document.getElementById('img_data')
          var img_path = data["img"]
          var final_content = follow_up;
          demoid.innerHTML = '<h3>Extracted Text</h3><p id="rcorners3">' + final_content + '</p>'
</script>

How can I show the uploaded image here, I have little experience with javascript so If anyone can help me on this!

what I tried so far is, I passed the image path URL, and using {% static %} tried to show the image like below

imgid.innerHTML = '<h3>Your Image</h3><img class="id-of-img-tag" src="" alt="img" style="width:300px;height:300px;margin-right:15px;">'
document.querySelector(".id-of-img-tag").src = "{% static " + img_path + " %}";

Answer

If the path to your image is valid, then you should create an image with the new Image() constructor. This is similar to doing document.createElement('img') to create an image. The constructor returns a HTMLImageElement instance, which is basically the JavaScript equivalent to the <img> element.

To ensure proper loading listen for the load event on the image. So that when the image has been downloaded you can add it to the page.

Then set the src property of the image (which will also set the attribute) to start the download of the image from your static folder.

...
var btnid = document.getElementById('btn-data')
var imgid = document.getElementById('img_data')
var img_path = data["img"]

var image = new Image();
image.addEventListener('load', function() {
  var title = document.createElement('h3');
  title.textContent = 'Your image';
  image.className = 'id-of-img-tag';
  image.alt = 'img';
  image.style.width = '300px';
  image.style.height = '300px';
  image.style.marginRight = '15px';
  imgid.append(title, image);
}, {once: true});
image.src = img_path;

var final_content = follow_up;
demoid.innerHTML = '<h3>Extracted Text</h3><p id="rcorners3">' + final_content + '</p>'


Source: stackoverflow