在django中显示图像 - javascript

我有一个Django Web应用程序,我在其中上传图像并显示一些文本。但是上传后我无法在前端显示图像。

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>

我如何在这里显示上传的图片,我对javascript的了解很少,所以如果有人可以帮助我!

到目前为止,我尝试的是传递图像路径URL,并使用{%static%}尝试显示如下图像

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 + " %}";

参考方案

如果图像的路径有效,则应使用new Image()构造函数创建图像。这类似于执行document.createElement('img')创建图像。构造函数返回一个HTMLImageElement实例,该实例基本上是与<img>元素等效的JavaScript。

为了确保正确加载,请监听图像上的load事件。这样,当图像下载完成后,您可以将其添加到页面中。

然后设置图像的src属性(还将设置属性),以开始从静态文件夹下载图像。

...
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>'

如何使整个<div>可选? - javascript

我看过几篇有关使整个div可点击的文章,但我希望使其成为可选择的。我所拥有的是一个php while循环,该循环显示基于用户进入mySQL数据库的表。该代码如下所示: <div class='tracksub'> <div class='headname'><div class='…

当<form>'.submit'函数被覆盖时(使用Ajax)将数据获取到php吗? - javascript

我已覆盖此网页上表单的.submit函数,因为该网页已加载在“ index.php”中的#mainContent内,并且我希望“提交”按钮仅替换此#mainContent。我正在尝试将数据从此表单获取到.php文件,以便对数据库进行查询(或简单地回显已填充的变量,以指示已传递数据)。我是AJAX的新手。有人可以向我解释如何将数据传递到.php文件,或者指向要…

使用php重新加载内容 - javascript

在对网站进行编程时,我以前使用过此代码,它可以完美工作,但是现在当我想使用一些Flash部件时,每次单击链接时,它都会重新加载所有网站。源代码: <!DOCTYPE html> <html> <head> <title>Hot King Staff</title> <meta charset=…

用jQuery填充模式形式 - javascript

我正在将订单表从数据库绘制到datatables(jquery插件)中。我要在每笔最后一笔交易或每笔交易中增加付款。问题是,如何获取单击添加付款按钮以添加付款的行的订单ID。其次,当点击addpayment时,它会弹出一个带有字段或订单号的模态表单。我想用在td中找到的订单ID填充该字段,并使其不可编辑或隐藏,但在提交模态表单时将其发布到服务器。表格和模式表…

保留文本区域的数据或值,然后选择输入 - javascript

通过$ _POST提交表单时,输入文件值仍然保留。像这样: if($_POST){ $error = false; if(!$post['price']){ $error = true; $error_note['price'] = "*Should not be empty"; } if($err…