使用FormData AngularJS的$ http和PHP上传文件时出错

时间:2018-08-31 20:37:58

标签: php angularjs http upload

指令

.directive('fileModel', ['$parse', function ($parse) {
return {
   restrict: 'A',
   link: function(scope, element, attrs) {
      var model = $parse(attrs.fileModel);
      var modelSetter = model.assign;

      element.bind('change', function(){
         scope.$apply(function(){
            modelSetter(scope, element[0].files[0]);
         });
      });
   }
};

控制器

.controller('MainController', ['fileUpload', fileUpload) {
   self.chainImgFile;
   self.uploadFile = function(type){
   if(type == 'hotelChain') {

        var result = fileUpload.uploadFileToUrl(self.chainImgFile, {type: 'hotelChain', hotelChainId: self.uploadChainId});

   } else {

        var result = fileUpload.uploadFileToUrl(self.hotelImgFile, {type: 'hotel', hotelChainId: null});
   } 

   self.showMessage(result); 
};

服务

.service('fileUpload', ['$http', function($http) {

this.uploadFileToUrl = function(file, extraData) {

   var fd = new FormData();
   fd.append(extraData.type, file);

   return $http.post(FILES_UPLOAD_URL, fd, {
      transformRequest: angular.identity,
      headers: {'Content-Type': undefined}
   });
};
}]);

HTML

<form name="newDataForm" novalidate>
    <div layout="column">
                <label class="btn btn-outline-primary">
                      <span>Image</span>
                        <input type="file" file-model="MainController.chainImgFile"/>
                        <button ng-click="MainController.uploadFile('hotelChain')">Upload File</button>
                </label>

            </div>
</form>

PHP

$uploadPrefix = 'upl';
$tempPath = $_FILES['hotelChain']['tmp_name'];
    $fileExtension = explode(".", $_FILES['hotelChain']['name']);
    $uploadPath = '../../uploads/logos/hotelChains/' . $uploadPrefix . "." . end($fileExtension);
move_uploaded_file($tempPath, $uploadPath);

我正在尝试使用上述代码上传图像,我在控制台中选中了IVE,当我单击“上传”按钮时,文件出现在“网络”选项卡中,但是什么也没发生,有潜在客户吗?我如何检查一切是否都正确发送以及PHP文件是否获取了图像?

0 个答案:

没有答案