JS realizes three methods of uploading pictures and preview pictures

Posted by Phpdiot on Tue, 07 Jan 2020 08:21:43 +0100

In the common user registration page, users need to select a picture locally as their avatar and preview it at the same time.

There are two common ideas: first, upload the image to the temporary folder of the server, return the url of the image, and then render it on the html page;

Another idea is to preview the image directly in the local memory, and upload it to the server for saving after the user confirms the submission.

These two methods have their own advantages and disadvantages. The first method is obvious, which wastes traffic and server resources; the second method increases the burden of browser, and requires higher compatibility of browser (not supported by IE in some lower versions).

The following are the ways to realize the above ideas:

1. Template file

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <div style="margin-left: 30px; margin-top: 30px">
    <form action="">
      {% csrf_token %}
    <h3>User registration</h3>
    <p>User name:<input type="text" name="userName"></p>
    <p>Password:<input type="password" name="password"></p>
    <p>Mailbox:<input type="text" name="email"></p>
      <input id="avatar" type="text" value="/static/images/sample.png" name="avatar" style="width: 400px"> {# In practical application, the input Tag hidden, display:none; #}
      <p><input type="submit" value="register"></p>
      </form>
    <div style="position: absolute; top: 85px; left: 300px;">
    <input id="avatarSlect" type="file" style="position: absolute;float: left; z-index: 10; opacity: 0;width: 100px; height: 100px;">
    <img id="avatarPreview" src="/static/images/sample.png" title="Click change picture" style="position: absolute; z-index: 9; float: left; width: 100px; height: 100px">
      </div>
  </div>
</body>
<script src="/static/jquery-3.2.1.js"></script>
<script>
  $(function () {
      bindAvatar();
 });
  function bindAvatar() {
      if(window.URL.createObjectURL){
        bindAvatar3();
      }else if(window.FileReader){
        bindAvatar2();
      }else {
        bindAvatar1();
      }
 }
  /*Ajax Upload to the background and return the url of the picture*/
  function bindAvatar1() {
    $("#avatarSlect").change(function () {
    var csrf = $("input[name='csrfmiddlewaretoken']").val();
    var formData=new FormData();
    formData.append("csrfmiddlewaretoken",csrf);
    formData.append('avatar', $("#Avatarslice ") [0]. Files [0]; / * get the uploaded image object*/
    $.ajax({
      url: '/upload_avatar/',
          type: 'POST',
          data: formData,
          contentType: false,
          processData: false,
          success: function (args) {
        console.log(args);  /*Image address of server*/
              $("#avatarPreview").attr('src','/'+args); / * preview picture*/
              $("#avatar").val('/'+args); / * assign the image url of the server to the hidden input tag of the form form*/
     }
      })
 })
  }
  /*window.FileReader Local Preview*/
  function bindAvatar2() {
    console.log(2);
       $("#avatarSlect").change(function () {
           var obj=$("#avatarSlect")[0].files[0];
           var fr=new FileReader();
           fr.onload=function () {
               $("#avatarPreview").attr('src',this.result);
               console.log(this.result);
               $("#avatar").val(this.result);
      };
      fr.readAsDataURL(obj);
    })
 }
 /*window.URL.createObjectURL Local Preview*/
 function bindAvatar3() {
   console.log(3);
      $("#avatarSlect").change(function () {
          var obj=$("#avatarSlect")[0].files[0];
          var wuc=window.URL.createObjectURL(obj);
           $("#avatarPreview").attr('src',wuc);
           $("#avatar").val(wuc);
{#           $("#avatarPreview").load(function () {#}/ * when the image is loaded, the memory space will be released, but an error will be reported in jQuery 3.2.1. The browser will release automatically when it is closed*/
{#               window.URL.revokeObjectURL(wuc);#}
{#      })#}
   })
 }
</script>
</html>

2. View function

from django.shortcuts import render, HttpResponse
def test(request):
  return render(request, 'test.html')
def upload_avatar(request):
  file_obj = request.FILES.get('avatar')
  file_path = os.path.join('static/images', file_obj.name)
  with open(file_path, 'wb') as f:
    for chunk in file_obj.chunks():
      f.write(chunk)
  return HttpResponse(file_path)

3. Routing system

from django.conf.urls import url
from django.contrib import admin
from home import views as homeViews
urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^upload_avatar/', homeViews.upload_avatar), # Upload your head
  url(r'^test/', homeViews.test), # Test page
]

Verification effect:

Before selecting a picture:

Ajax uploads the image to the server and returns the url of the image in the browser:

window.FileReader local preview, form form submission:

window.URL.createObjectURL local preview, form form form submission:

 

 

Reprinted from: https://www.jb51.net/article/118660.htm

Topics: Django JQuery IE