SoFunction
Updated on 2025-03-02

Web front-end development upload upload avatar js sample code

This time I will share a simple example of uploading avatar, the general process is:

1. Convert the selected image to a base64 string

function preview(file) {//Preview the picture to get the picture base64  var prevDiv = ('preview');
  if ( && [0]) {
   var reader = new FileReader();
    = function(evt){
     = '<img src="' +  + '" />';
   }
   ([0]);
  } else {
    = '<div class="img" style="filter:progid:(sizingMethod=scale,src=\'' +  + '\'"></div>';
  }
 }

The above method can convert the selected image to base64 preview. At this time, you can pile up to see what base64 is.

2. According to the upload requirements of (Ali Cloud), the image base64 is first-class.

var binaryblob = function (s, type) {//blob object     var byteString = atob(s);
     var array = [];
     for (var i = 0; i < ; i++) {
      ((i));
     }
     return new Blob([new Int8Array(array)], {type: type});
    };
var binaryPictureBlob = function (dataUrl, filterHead) {//Upload base64 to remove the head     var s = filterHead ? (/^data:image\/(png|jpeg|pjpeg|bmp|gif|x-png);base64,/, "") : dataUrl;
     return binaryblob(s, "image/jpeg");
    };

At this time, base64 is removed first and then returned a blob object for uploading to Alibaba Cloud. The above method is best written in service and factory. It is easy to call it directly when there is an image upload requirement in the future. Try not to write it in the controller.

3. First request

$=function(){//save var pic=binaryPictureBlob($('#preview img').attr('src'),true);//Calling this method to get uploaded data (pic);
 $http({//Interface parameters  url:'',
  method:'',
  headers:{},
  data:{}
 }).success(function(data){
  (data);
// Here we talk about making the second request }).error(function(err1,header1,config1,status1){//Processing response failed  (err1,header1,config1,status1);
 })
} 

The first request after clicking the save button is uploaded to the local server, which is actually uploading some tags and other information about the image. After successful upload, a Alibaba Cloud address corresponding to the image and an Alibaba Cloud uploaded image will be returned. At this time, the image address is temporarily unavailable.

4. The second request

$http({
 method:'PUT',
 url:,
 headers: {
  'Content-Type':' ',
 },
 data:pic// Image information blob after de-first process of image base64 string}).success(function(data2){
 $=;//Assign the URL of the server data to link the image}).error(function(err2,header2,config2,status2){//Processing response failed (err2,header2,config2,status2);
});

Notice:

At this time, the requested url is a fixed address returned by the first request (I am here-).

The header information department avoids the error when uploading Alibaba Cloud, write it as 'Content-Type':' ' or upload the header according to Alibaba Cloud's requirements.

After the second request is successful, the address of the image is the address of the image returned for the first time (it is a big pit here, don't write it).

5. It should be OK at this time, so enjoy the beautiful photos!

Finally, the complete code is attached, please give me advice!
Friendly tips: When copying the code to test, please add the parameters yourself!

<!DOCTYPE html>
<html ng-app="webPhotos">
<head lang="zh-CN">
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
 <title>photos</title>
 <style>
  div{text-align:center;border:1px solid #ddd;}
  button,div{margin:10px auto}
  button{border:0;width:200px;height:30px;line-height:30px;font-size:1pc;color:#333;background-color:#0ff;cursor:pointer;border-radius:5px}
  button:hover{background-color:#db7093}
  #preview,.show-img{width:200px;height:200px;}
  #preview img,.show-img img{width:100%;height:100%;}
  .file{position:relative;display:block;width:200px;height:30px;line-height:30px;background:#9acd32;border-radius:5px;margin:10px auto;overflow:hidden;color:#1e88c7;text-decoration:none;text-indent:0}
  .file input{position:absolute;font-size:75pt;right:0;top:0;opacity:0}
  .file:hover{background:#aadffd;border-color:#78c3f3;color:#004974;text-decoration:none}
 </style>
</head>
<body>
<div ng-controller="photos">
 <a href="javascript:;" class="file">
  <span>Select a file</span>
  <input type="file" onchange="preview(this)" />
 </a>
 <button class="save" ng-click="save()">save</button>
 <h2>Avatar preview</h2>
 <div ></div>
 <h2>Show avatar after successful upload</h2>
 <div class="show-img">
  <img ng-src={{imgSrc}} alt=""/>
 </div>
</div>
<script type="text/javascript" src="///jquery/1.11.3/"></script>
<script src="/libs//1.4.6/"></script>
<script>
 function preview(file) {//Preview the picture to get the picture base64  var prevDiv = ('preview');
  if ( && [0]) {
   var reader = new FileReader();
    = function(evt){
     = '<img src="' +  + '" />';
   }
   ([0]);
  } else {
    = '<div class="img" style="filter:progid:(sizingMethod=scale,src=\'' +  + '\'"></div>';
  }
 }
 //The above code is best written in service or factory ('webPhotos',['ng'])
   .controller('photos',function($scope,$http){
    var binaryblob = function (s, type) {//blob object     var byteString = atob(s);
     var array = [];
     for (var i = 0; i < ; i++) {
      ((i));
     }
     return new Blob([new Int8Array(array)], {type: type});
    };
    var binaryPictureBlob = function (dataUrl, filterHead) {//Upload base64 to remove the head     var s = filterHead ? (/^data:image\/(png|jpeg|pjpeg|bmp|gif|x-png);base64,/, "") : dataUrl;
     return binaryblob(s, "image/jpeg");
    };

    $=function(){//save     var pic=binaryPictureBlob($('#preview img').attr('src'),true);//Calling this method to get uploaded data $http({//Interface parameters      url:'',
      method:'',
      headers:{},
      data:{}
     }).success(function(data){//At this time, the upload to the local server was successful. In fact, it was just uploading the tag related to this image. The image information has not been uploaded yet.      $http({
       method:'PUT',
       url:,//The address has been generated when uploading to the local server, but the address must be uploaded to Alibaba Cloud before the uploading image will be effective.       headers: {
        'Content-Type':' ',//Avoid errors when uploading Alibaba Cloud or uploading header according to Alibaba Cloud's requirements       },
       data:pic//Image base64 string after de-first image information      }).success(function(data2){//Upload image information from the server to Alibaba Cloud       $=;//Assign the URL of the server data to link the image      }).error(function(err2,header2,config2,status2){//Processing response failed       (err2,header2,config2,status2);
      });
     }).error(function(err1,header1,config1,status1){//Processing response failed      (err1,header1,config1,status1);
     })
    }
   })
</script>
</body>
</html>

For more exciting content, please refer to the topic"Asume of ajax upload technology""Javascript file upload operation summary"and"JQuery Upload Operation Summary"Conduct learning.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.