简体   繁体   中英

File upload doesn't work - AngularJS and PHP

I'm using angularJS and PHP to upload file. From angularJS part I'm sending a blob url like this:

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

and on PHP side I'm trying to get file from blob url and save it on local storage.

Here is my code on server side:

$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() function is returning failed to open stream: Invalid argument . When I put in browser that URL the pdf file is loading correctly.

Does anyone have an idea how to fix this or to use another way to read file from specified blob url.

Thanks in advance!

Blob URL's are only a temporary URL and no longer exist when you close the tab. They only exist in the space of the browser you're using and cannot be accessed from your server.

Instead of passing the URL to your server you need to pass the actual file data. First you need to get the data from the blob URL like so:

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();

Then upload the blob data to server:

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);
}

Now you can read the data like a normal form $_POST['thefile'] and $_FILES['thefile']

PHP does not know how to work with blob: URLs. You need to strip that from the $blob :

$realBlobUrl = substr($blob, 5);

and fetch that one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM