javascript - 在 django 中显示图像

标签 javascript python html django

我有一个 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>'

关于javascript - 在 django 中显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60503105/

相关文章:

javascript - 自定义属性不起作用

javascript - Node : Does a writable stream wait for the drain event automatically before writing again?

python - 基本 Python 数据结构接口(interface)的测试

html - 如何在 Safari 中将 flex 容器的绝对定位子项居中?

javascript - HTML 编码顺序与布局问题

javascript - Jquery .append 和appendto() 悲伤

python - 如何允许脚本被执行但不被读取?

python - Python 2 中的 TicTacToe 项目 : I am trying to avoid using global variables and return variables instead

javascript - 有没有更有效的方式来显示 DOM 元素

html - Zurb Foundation - 滑出式菜单