I try to upload a file by encoding the content as base64 using a meteor app and a custom php script.
The php script is the following:
require_once '../vendor/autoload.php';
use WindowsAzure\Common\ServicesBuilder;
use MicrosoftAzure\Storage\Common\ServiceException;
use MicrosoftAzure\Storage\Blob\Models\ListBlobsOptions;
error_log("Method:".$_SERVER['REQUEST_METHOD'],0);
if($_SERVER['REQUEST_METHOD'] === 'OPTIONS'){
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');
error_log("Options Called",0);
die();
} else {
error_log("Post Called",0);
function create_storage_connection()
{
return "DefaultEndpointsProtocol=https;AccountName=".getenv('AZURE_ACCOUNT').";AccountKey=".getenv('AZURE_KEY');
}
$connectionString=create_storage_connection();
$blobRestProxy= ServicesBuilder::getInstance()->createBlobService($connectionString);
$container_name=getenv('AZURE_CONTAINER');
$data=file_get_contents('php://input');
$data=json_decode($data,true);
try{
//Upload data
$file_data=base64_decode($data['data']);
$data['name']=uniqid().$data['name'];
$blobRestProxy->createBlockBlob($container_name,$data['name'],$file_data);
$blob = $blobRestProxy->getBlob($container_name, $data['name']);
//Download url info
$listBlobsOptions = new ListBlobsOptions();
$listBlobsOptions->setPrefix($data['name']);
$blob_list = $blobRestProxy->listBlobs($container_name, $listBlobsOptions);
$blobs = $blob_list->getBlobs();
$url=[];
foreach($blobs as $blob)
{
$urls[]=$blob->getUrl();
}
error_log("Urls:\n".implode(" , ",$urls),0);
header("Content-type: application/json");
$result=json_encode(['files'=>"sent",'url'=>$urls]);
error_log("Result: ".$result,0);
echo $result;
} catch(ServiceException $e) {
$code = $e->getCode();
$error_message = $e->getMessage();
header("Content-type: application/json");
echo json_encode(['code'=>$code,'message'=>$error_message]);
}
}
And on my meteor script I created a file named "imports/ui/File.jsx" having the following content:
import React, { Component } from 'react';
import {FileUpload} from '../api/FileUpload.js';
class File extends Component {
changeFile(e) {
e.preventDefault()
let files = document.getElementById('fileUpload');
var file = files.files[0];
var reader=new FileReader();
reader.onloadend = function() {
Meteor.call('fileStorage.uploadFile',reader.result,file.name,file.type)
}
reader.readAsDataURL(file);
}
render() {
return (
<form onSubmit={ this.changeFile.bind(this) }>
<label>
<input id="fileUpload" type="file" name="file" />
</label>
<button type="submit">UploadFile</button>
</form>
)
}
}
export default File;
And I also have a file named imports/api/FileUpload.js
that handles the http call to the server:
import { Meteor } from 'meteor/meteor';
import { HTTP } from 'meteor/http'
export default Meteor.methods({
'fileStorage.uploadFile'(base64Data,name,mime) {
// this.unblock();
let http_obj={
'data':{
'data':base64Data,
'name':name,
'mime':mime
},
}
HTTP.call("POST","http://localhost/base64Upload/",http_obj,function(err,response){
console.log("Response:",response);
});
}
});
The problem is even though I get I successfull response from my server the:
console.log("Response:",response);
Does not print the returned json response from my server script to the console. Instead I get the following message (in my browser console):
Response: undefined
I cannot uinderstand why I get undefined on response even though the php script returns a response. Also if I console.log
the err I get the following:
Error Error: network Καταγραφή στοίβας: httpcall_client.js/HTTP.call/xhr.onreadystatechange@http://localhost:3000/packages/http.js?hash=d7408e6ea3934d8d6dd9f1b49eab82ac9f6d8340:244:20
And I cannot figure out why does it happen.
The meteor App does 2 Http calls 1 using OPTIONS
method and one that uses POST
As requested when replaced the die()
with:
var_dump($_SERVER['REQUEST_METHOD']); exit;
I get the response:
/home/pcmagas/Kwdikas/php/apps/base64Upload/src/public/index.php:14:string 'OPTIONS' (length=7)
Also on my network tab of the browser it says:
Please keep in mind that the meteor performs 2 http calls to the script one using http OPTIONS
method and one that uses the http POST
one. What I want to get is the one that uses the http POST
one.
I also tried to put a timeout of 2 seconds by changing the http_obj
into:
let http_obj={
'data':{
'data':base64Data,
'name':name,
'mime':mime
},
'timeout':2000
}
But I get the following error:
Error Error: Can't set timers inside simulations
In the end I needed to make the method to run on server:
I did it by changing the imports/api/FileUpload.js
into this: (I also removed unwanted code)
import { Meteor } from 'meteor/meteor';
import { HTTP } from 'meteor/http'
export const UploadedFile=null;
if(Meteor.isServer){
Meteor.methods({
'fileStorage.uploadFile'(base64Data,name,mime) {
// this.unblock();
let http_obj={
'data':{
'data':base64Data,
'name':name,
'mime':mime
},
// 'timeout':2000,
'headers':{
'Content-Type': 'application/json'
}
}
return HTTP.call("POST","http://localhost/base64Upload/",http_obj);
}
});
}
And putting this require into server/main.js
resulting into this:
import { Meteor } from 'meteor/meteor';
import {FileUpload} from '../imports/api/FileUpload.js';
Meteor.startup(() => {
// code to run on server at startup
});
Also on imports/ui/File.jsx
I call the method like that:
Meteor.call('fileStorage.uploadFile',reader.result,file.name,file.type,function(err,response){
console.log(response);
})
}