使用javascript在django中上传和显示预览

时间:2016-04-08 08:17:00

标签: javascript django image-uploading

我正在使用表单上传照片并在<img>中显示 但它无法正常工作,无法在<img>上显示照片 我正在使用Django,我有一个base.html作为模板,我通过以下方式添加了这个javascript:

<script src="{% static "landingpages/js/photoupload.js" %}"></script>

并且用户正在根据需要生成

的Javascript

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#myimg').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$(function () { //document ready call
    $("#photoinput").change(function(){
        readURL(this);
    });
});

HTML

<section class="container" xmlns="http://www.w3.org/1999/html">
  <div class="row addform" id="addform">
    <div class="col-md-12 addform-col">
      <div id="headertag" class="row" style="margin-left: 0px">
        <label class="add-lable">Team Member(s):
          <span style="color:red">*</span>
        </label>
      </div>
      <div class="row input-field">
        <form id="form1" runat="server">
          <div name="membercard" class="row">
            <div id="teamform" class="col-md-4" style="display: none">
              <div name="imageholder" class="row tm-image-holder">
                <div class="col-md-12" style="text-align: center">
                  <img id="myimg" style="height: 200px;text-align: center;">
                </div>
               </div>
               <input id="photoinput" type="file" class="btn btn-block btn-lg btn-primary inout-margin mybut">
               <input id="name" name="name0" type="text" class="add-input input-margin" placeholder="Name, Mohammad, ... *">
               <input id="job" name="job0" type="text" class="add-input" placeholder="Job, Developer, Designer, ... *">
               <textarea id="explain" name="explain0" class="add-textarea input-margin" rows="4" placeholder="Explain this member in 2 to 4 lines *"></textarea>
              </div>
              <span id="formhere"></span>
             </div>
            </form>
            <div name="addform" class="row input-field">
              <div class="col-md-12" style="text-align: left">
                <a onclick="member_card()">+ Add Team Member</a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

1 个答案:

答案 0 :(得分:1)

将选项enctype="multipart/form-data"添加到form元素,如下所示:

<form id="form1" enctype="multipart/form-data runat="server">

正如Django文档所说:

  

请注意,如果请求方法是POST,则request.FILES将仅包含数据,并且发布请求的请求具有enctype =“multipart / form-data”属性。否则,request.FILES将为空。

https://docs.djangoproject.com/en/1.9/topics/http/file-uploads/