栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将上传的图像发送到服务器并将其保存在服务器中

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将上传的图像发送到服务器并将其保存在服务器中

假设您在后端中期望Multipart,这是一段对我有用的代码。

这是一个jsfiddle。

var app = angular.module('myApp', [])app.controller('MyController',  function MyController($scope, $http) {    //the image    $scope.uploadme;    $scope.uploadImage = function() {      var fd = new FormData();      var imgBlob = dataURItoBlob($scope.uploadme);      fd.append('file', imgBlob);      $http.post(          'imageURL',          fd, { transformRequest: angular.identity, headers: {   'Content-Type': undefined }          }        )        .success(function(response) {          console.log('success', response);        })        .error(function(response) {          console.log('error', response);        });    }    //you need this function to convert the dataURI    function dataURItoBlob(dataURI) {      var binary = atob(dataURI.split(',')[1]);      var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];      var array = [];      for (var i = 0; i < binary.length; i++) {        array.push(binary.charCodeAt(i));      }      return new Blob([new Uint8Array(array)], {        type: mimeString      });    }  });//your directiveapp.directive("fileread", [  function() {    return {      scope: {        fileread: "="      },      link: function(scope, element, attributes) {        element.bind("change", function(changeEvent) {          var reader = new FileReader();          reader.onload = function(loadEvent) { scope.$apply(function() {   scope.fileread = loadEvent.target.result; });          }          reader.readAsDataURL(changeEvent.target.files[0]);        });      }    }  }]);<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><div ng-app="myApp">  <div ng-controller="MyController">    <input type="file" fileread="uploadme" />    <img src="{{uploadme}}" width="100" height="50" alt="Image preview...">    <br/>    <p>      Image dataURI:      <pre>{{uploadme}}</pre>    </p>    <br/>    <button ng-click="uploadImage()">upload image</button>  </div></div>

请注意 以下部分:

{    transformRequest: angular.identity,    headers: {        'Content-Type': undefined    }}

是一些Angular魔术,为了使$ http解析FormData并找到正确的内容类型,等等。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/388257.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号