2017-07-14 58 views
0

我正在使用angularJS和PHP來上傳文件。從angularJS部分我送斑點網址是這樣的:文件上傳不起作用 - AngularJS和PHP

{ 
    $ngfBlobUrl: "blob:http://test.dev/91458ff7-fc18-4bbc-8dae-f06941e0a1c9" 
    selectedCategory: "1", 
    name: "some_file_name.pdf" 
} 

和PHP方面我想從BLOB網址獲取文件並將其保存在本地存儲。

這是我在服務器端代碼:

$blob = $file['$ngfBlobUrl']; 
$f_name = $file['name']; 
$filename = uniqid() . '_' .$f_name; // generate unique file name 

if(@file_put_contents($destination.'/'.$filename, @file_get_contents($blob))) 
{ 
    // do something! 
} 

的file_get_contents()函數返回未能打開流:無效的參數。當我在瀏覽器中加載PDF文件時,URL是正確的。

有沒有人有一個想法如何解決這個問題或使用另一種方式從指定的BLOB網址讀取文件。

在此先感謝!

+0

'$ file'從哪裏來? – cweiske

+0

$ file = $ request-> documents;我使用laravel和Request對象來讀取json。 –

+0

$ request->文檔代表上面的對象。 –

回答

1

Blob URL只是一個臨時URL,在關閉該選項卡時不再存在。它們只存在於您正在使用的瀏覽器空間中,無法從您的服務器訪問。

而不是將URL傳遞到您的服務器,您需要傳遞實際的文件數據。 首先,你需要從團塊URL獲取數據,像這樣:

var xhr = new XMLHttpRequest(); 
xhr.open('GET', 'YOUR BLOB URL HERE'); 
xhr.responseType = 'blob'; 
xhr.onload = function(e) { 
    if (this.status == 200) { 
    var blobFileData = this.response; //This has the actual data 
    //now send to server (code below) 
    uploadFile(blobFileData); 
    } 
}; 
xhr.send(); 

BLOB數據然後上傳到服務器:

function uploadFile(blobFileData){ 
    var xhr = new XMLHttpRequest(); 
    xhr.open("POST", "YOUR SERVER URL HERE"); 
    var formdata = new FormData(); 
    formdata.append("thefile", blobFileData, "YOUR FILE NAME HERE"); 
    xhr.onreadystatechange = function() { 
     if (xhr.readyState == 4 && xhr.status == 200) { 
      //success 
     } 
    } 
    xhr.send(formdata); 
} 

現在,您可以讀取數據像一個正常的形式 $ _ POST ['thefile']和$ _FILES ['thefile']

+0

這有道理......謝謝。 –

0

PHP不知道如何使用blob:網址。您需要從$blob中刪除:

$realBlobUrl = substr($blob, 5); 

並提取該文件。

+0

當我使用你的代碼時,我得到:{「error」:「file_get_contents(http:\/\/test.dev \/91458ff7-fc18-4bbc-8dae-f06941e0a1c9):無法打開流:HTTP請求失敗! HTTP \ /1.0 404 Not Found \ r \ n「} –

+0

您是否有其他解決方案? –