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 = '<img src="' + evt.target.result + '" />'; } reader.readAsDataURL(file.files[0]); } else { prevDiv.innerHTML = '<div class="img" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div>'; } }
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($('#preview img').attr('src'),true);//调用该方法得到上传数据 console.log(pic); $http({//接口参数 url:'', method:'', 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:'PUT', url:data.UrlForPut, headers: { 'Content-Type':' ', }, 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(&#39;preview&#39;); 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;; } } //以上代码最好写在service或factory里 angular.module('webPhotos',['ng']) .controller('photos',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($('#preview img').attr('src'),true);//调用该方法得到上传数据 $http({//接口参数 url:'', method:'', headers:{}, data:{} }).success(function(data){//此时上传到本地服务器成功,实际上只是上传了与此图片有关的标记,图片信息还未上传 $http({ method:'PUT', url:data.UrlForPut,//上传到本地服务器已经生成地址,但要上传到阿里云后地址才生效有上传的图像显示 headers: { 'Content-Type':' ',//避免阿里云上传时报错或者根据阿里云要求上传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>