2016-10-05 95 views
0

我已經使用了這個問題,但沒有找到答案。我正在使用ng-file-upload Angular指令將圖像上傳到我的後端。在後端我使用PHP來檢索圖像。如果我選擇一個不包含空格的圖像,它可以正常工作。但是,如果我選擇包含空白的圖像,則會引發錯誤。這是我做過什麼當文件名包含空格時文件上傳失敗

//app.js 
         Upload.upload({ 
         url: "api/index.php/postNewFeedsWithPicture", 
           file: $scope.file, 
           method: "post" 
           }).then(function (response) { 
           $scope.isShowing = false; 
           if (response.data.error) { 
            toastr.options = {positionClass: 'toast-bottom-full-width'}; 
            toastr.error(response.data.message, {timeOut: 5000}); 
           } 
           else { 
            toastr.options = {positionClass: 'toast-bottom-full-width'}; 
            toastr.success(response.data.message, {timeOut: 5000}); 
            $scope.file = null; 

           } 

          }, function (reason) { 
           $scope.isShowing = false; 
           toastr.options = {positionClass: 'toast-bottom-full-width'}; 
           toastr.error('Message not posted! Network error', {timeOut: 5000}); 
          });       

在我的html文件,我在我的PHP文件做這個

<div role="button" ngf-select ng-model="file" name="file" ngf-pattern="'image/*'" ngf-accept="'image/*'" ngf-max-size="20MB">Upload</div> 

我寫的保存圖像

function savePictureToDb($fileName, $dirName) { 
$target_dir = "../image/" . $dirName . "/"; 
$target_file = $target_dir . basename($_FILES[$fileName]["name"]); 
$uploadOk = 1; 
$errorMsg = null; 
$report = array(); 
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION); 
// Check file size. //20mb 
if ($_FILES[$fileName]["size"] > 20000000) { 
    $uploadOk = 0; 
    $errorMsg = "File size is greater than 20 mega bytes"; 
} 
// Allow certain file formats 
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") { 
    $uploadOk = 0; 
    $errorMsg = "The file selected is not an image"; 
} 
if ($uploadOk == 0) { 
    $report[ERROR] = TRUE; 
    $report[MESSAGE] = $errorMsg; 
    return $report; 
    // if everything is ok, try to upload file 
} else { 
    if (move_uploaded_file($_FILES[$fileName]["tmp_name"], $target_file)) { 
     rename($target_file, $target_dir . generateRandStr_md5(500) . "." . $imageFileType); 
     $response['path'] = basename($_FILES[$fileName]["name"]); 
     $report[ERROR] = FALSE; 
     $report[PATH] = $response['path']; 
     return $report; 
    } else { 
     $errorMsg = "Unexpected error"; 
     $report[ERROR] = TRUE; 
     $report[MESSAGE] = $errorMsg; 
     return $report; 
    } 
} 

}

功能它工作正常,但如果圖像包含空白空間,這是我調試時得到的錯誤

array (
    'file' => 
    array (
    'name' => 'Age Declaration.jpg', 
    'type' => '', 
    'tmp_name' => '', 
    'error' => 1, 
    'size' => 0, 
), 
) 
+0

可以使用$ TARGET_FILE = $ TARGET_DIR重命名文件名隨機值

$filename1=explode(".", $file); $extension=end($filename1); $file=rand().time().".".$extension; 

或使用PATHINFO()。 (串)基名($ _ FILES [$文件名] [ 「名稱」]); –

回答

0

爲extention

$ext = pathinfo($filename, PATHINFO_EXTENSION);