Home  >  Article  >  Web Front-end  >  Web front-end development upload upload avatar js sample code

Web front-end development upload upload avatar js sample code

高洛峰
高洛峰Original
2016-12-09 13:15:021096browse

This time I share a simple example of uploading an avatar. The general process is:

1. Convert the selected image to a base64 string

function preview(file) {//预览图片得到图片base64
    var prevDiv = document.getElementById('preview');
    if (file.files && file.files[0]) {
      var reader = new FileReader();
      reader.onload = function(evt){
        prevDiv.innerHTML = &#39;<img src="&#39; + evt.target.result + &#39;" />&#39;;
      }
      reader.readAsDataURL(file.files[0]);
    } else {
      prevDiv.innerHTML = &#39;<div class="img" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\&#39;&#39; + file.value + &#39;\&#39;"></div>&#39;;
    }
  }

The above method can convert the selected image into a base64 preview. This You can use piling to see what base64 is.

Second, according to (Alibaba Cloud) upload requirements, base64 de-first-class processing of the image

var binaryblob = function (s, type) {//blob对象
          var byteString = atob(s);
          var array = [];
          for (var i = 0; i < byteString.length; i++) {
            array.push(byteString.charCodeAt(i));
          }
          return new Blob([new Int8Array(array)], {type: type});
        };
var binaryPictureBlob = function (dataUrl, filterHead) {//上传base64去头
          var s = filterHead ? dataUrl.replace(/^data:image\/(png|jpeg|pjpeg|bmp|gif|x-png);base64,/, "") : dataUrl;
          return binaryblob(s, "image/jpeg");
        };

At this time, base64 is de-first-class processed and a blob object is returned for uploading to Alibaba Cloud. It is best to write the above methods in the service and factory, so that they can be called directly when there is a need to upload images in the future. Try not to write them in the controller.

3. First request

$scope.save=function(){//保存
  var pic=binaryPictureBlob($(&#39;#preview img&#39;).attr(&#39;src&#39;),true);//调用该方法得到上传数据
  console.log(pic);
  $http({//接口参数
    url:&#39;&#39;,
    method:&#39;&#39;,
    headers:{},
    data:{}
  }).success(function(data){
    console.log(data);
      //这里讲进行第二次请求
  }).error(function(err1,header1,config1,status1){//处理响应失败
    console.log(err1,header1,config1,status1);
  })
}

After clicking the save button, the first request is to upload to the local server. It actually uploads some information such as tags of the image. After the upload is successful, an Alibaba Cloud address corresponding to the image and an Alibaba Cloud uploaded image address will be returned. At this time, the image address is temporarily unavailable.

4. The second request

$http({
  method:&#39;PUT&#39;,
  url:data.UrlForPut,
  headers: {
    &#39;Content-Type&#39;:&#39; &#39;,
  },
  data:pic//图像base64字符串去头等处理后的图片信息blob
}).success(function(data2){
  $scope.imgSrc=data.Url;//将服务器的数据的url赋值图片链接
}).error(function(err2,header2,config2,status2){//处理响应失败
  console.log(err2,header2,config2,status2);
});

Note:

The URL requested at this time is a fixed address returned by the first request (here I am --data.UrlForPut).

To avoid Alibaba Cloud uploading errors, write 'Content-Type':' ' in the header information or upload the header according to Alibaba Cloud's requirements.

After the second request is successful, the address of the image will be the address of the image returned for the first time (this is a big pit, do not write data.Url as data2.Url).

5. Everything should be ok at this point, enjoy the beautiful photos!

Attach the complete code at the end, hope you can give me some advice!
Friendly reminder: When copying the code for testing, please add the request parameters yourself!




  
  
  photos
  


选择文件

头像预览

上传成功后展示头像

<script> function preview(file) {//预览图片得到图片base64 var prevDiv = document.getElementById(&amp;#39;preview&amp;#39;); if (file.files &amp;&amp; file.files[0]) { var reader = new FileReader(); reader.onload = function(evt){ prevDiv.innerHTML = &amp;#39;&lt;img src=&quot;&amp;#39; + evt.target.result + &amp;#39;&quot; /&gt;&amp;#39;; } reader.readAsDataURL(file.files[0]); } else { prevDiv.innerHTML = &amp;#39;&lt;div class=&quot;img&quot; style=&quot;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\&amp;#39;&amp;#39; + file.value + &amp;#39;\&amp;#39;&quot;&gt;&lt;/div&gt;&amp;#39;; } } //以上代码最好写在service或factory里 angular.module(&#39;webPhotos&#39;,[&#39;ng&#39;]) .controller(&#39;photos&#39;,function($scope,$http){ var binaryblob = function (s, type) {//blob对象 var byteString = atob(s); var array = []; for (var i = 0; i < byteString.length; i++) { array.push(byteString.charCodeAt(i)); } return new Blob([new Int8Array(array)], {type: type}); }; var binaryPictureBlob = function (dataUrl, filterHead) {//上传base64去头 var s = filterHead ? dataUrl.replace(/^data:image\/(png|jpeg|pjpeg|bmp|gif|x-png);base64,/, "") : dataUrl; return binaryblob(s, "image/jpeg"); }; $scope.save=function(){//保存 var pic=binaryPictureBlob($(&#39;#preview img&#39;).attr(&#39;src&#39;),true);//调用该方法得到上传数据 $http({//接口参数 url:&#39;&#39;, method:&#39;&#39;, headers:{}, data:{} }).success(function(data){//此时上传到本地服务器成功,实际上只是上传了与此图片有关的标记,图片信息还未上传 $http({ method:&#39;PUT&#39;, url:data.UrlForPut,//上传到本地服务器已经生成地址,但要上传到阿里云后地址才生效有上传的图像显示 headers: { &#39;Content-Type&#39;:&#39; &#39;,//避免阿里云上传时报错或者根据阿里云要求上传header }, data:pic//图像base64字符串去头等处理后的图片信息 }).success(function(data2){//将图像信息从服务器上传到阿里云 $scope.imgSrc=data.Url;//将服务器的数据的url赋值图片链接 }).error(function(err2,header2,config2,status2){//处理响应失败 console.log(err2,header2,config2,status2); }); }).error(function(err1,header1,config1,status1){//处理响应失败 console.log(err1,header1,config1,status1); }) } }) </script>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn