I am writing code to test the file upload using PHPUnit in Laravel 5.3. I am JWT and I am sending the token in the header (HTTP_Authorization), but the token is not reaching the server. The code is given below.
Please tell me what is wrong with my code?
public function testUpload()
{
$content = $this->post('users/login', ['password' => 'mypass',
'email' => 'scko#gmail.com'])->response->getContent();
$data = json_decode($content);
$token = $data->token;
$stub = 'D:/work/gw.png';
$name = str_random(8).'.png';
$path = 'D:/storage/userfiles/78/'.$name;
copy($stub, $path);
$file = new \Illuminate\Http\UploadedFile($path, $name, filesize($path), 'image/png', null, true);
$response = $this->call('POST', 'files/uploadcardimage', ['HTTP_Authorization' => $token], [] ['file' => $file], ['Accept' => 'application/json']);
$content = json_decode($response->getContent());
echo json_encode($content);
die;
}
Related
I'm trying to upload files via API, in POSTMAN I can do it perfectly. However when doing in my application is not accepted.
Store in Controller:
public function store(Request $request)
{
$data = $request->validate([
'projeto_id' => 'required|integer',
'name' => 'required|string|max:255',
'logo' => 'nullable|image|mimes:jpeg,png,jpg|max:2000',
'telephone' => 'required|string|max:255',
'desc' => 'required|string',
'quantity' => 'required|integer|gt:0|lt:51',
'sequential' => 'required|integer|gt:0',
]);
$user = Auth::user()->id;
if($user != Auth::id()){
abort(403);
}
//UPLOAD IMAGEM DO GRUPO
$logo = $request['logo'];
// Check if a profile image has been uploaded
if ($request->has('logo')) {
// Get image file
$image = $request->file('logo');
// Make a image name based on user name and current timestamp
$name = Str::slug($user.'_'.time());
// Define folder path
$folder = '/uploads/images/'.$user.'/groupimg/logo/';
// Make a file path where image will be stored [ folder path + file name + file extension]
$filePath = $folder . $name. '.' . $image->getClientOriginalExtension();
// Upload image
$this->uploadOne($image, $folder, 'public', $name);
// Set user profile image path in database to filePath
$logo = $filePath;
}
$gPrivado = '0';
if($request->has('private')){
$gPrivado = '1';
}
$i = 0;
$delayCounter = 0;
$sequential = $data['sequential'];
while ($i < (int)$data['quantity']) {
$delay = $delayCounter + rand(10, 15);
CreateGroups::dispatch($data['name'] . " {$sequential}", $logo , $data['desc'], $gPrivado, [$data['telephone']], $data['projeto_id'], auth()->user())
->delay(Carbon::now()
->addSeconds($delay));
$delayCounter = $delay;
$i++;
$sequential++;
}
return redirect()->back()->with('success', 'Grupos adicionados em fila de criação, aguarde alguns minutos .');
}
Use Job to proccess:
public function handle()
{
$user = $this->user;
if ($user->instance_connected) {
$ZApi = new ZApi($user->zapi_instance_id, $user->zapi_token);
$createdGroup = $ZApi
->createGroup($this->name, $this->phones);
sleep(3);
foreach($createdGroup->groupInfo as $informacoes){
$linkInvite = $ZApi->getGroupInvite($informacoes->id);
$idGroup = $informacoes->id;
}
//DESCRICAO DO GRUPO
$descricao = $this->desc;
$setDescricao = $ZApi->setGroupDescription($idGroup, $descricao);
//GRUPO PRIVADO
if ($this->private == '1'){
$grupoPrivado = $ZApi->setGroupMessages($idGroup, 'true');
$adminOnly = $ZApi->setGroupEdit($idGroup, 'true');
}
$setImg = $ZApi->groupImage($idGroup, $this->logo);
The last line send to API, I'm using Guzzle
And this is my API function
public function groupImage(string $groupId, string $value)
{
return $this->doRequest2('POST', "group-pic", [
'multipart' => [
[
'name' => 'phone',
'contents' => $groupId,
],
[
'Content-type' => 'multipart/form-data',
'name' => 'file',
'contents' => fopen('storage'.$value, 'r'),
]
]
]);
}
But get this error response
GuzzleHttp\Exception\ClientException Client error: POST http://localhost:8081/api/danilo/group-pic resulted in a 400 Bad Request response: {"status":"Error","message":"File parameter is
required!"}
Can someone help me?
Based on the sdk code, the s3 client code uses retry logic, but the sample code from the docs suggest doing a loop until the multipart upload finishes correctly.
$s3Client = new S3Client([
'profile' => 'default',
'region' => 'us-east-2',
'version' => '2006-03-01'
]);
$bucket = 'your-bucket';
$key = 'my-file.zip';
// Using stream instead of file path
$source = fopen('/path/to/large/file.zip', 'rb');
$uploader = new ObjectUploader(
$s3Client,
$bucket,
$key,
$source
);
do {
try {
$result = $uploader->upload();
if ($result["#metadata"]["statusCode"] == '200') {
print('<p>File successfully uploaded to ' . $result["ObjectURL"] . '.</p>');
}
print($result);
} catch (MultipartUploadException $e) {
rewind($source);
$uploader = new MultipartUploader($s3Client, $source, [
'state' => $e->getState(),
]);
}
} while (!isset($result));
Is that MultipartUploadException being thrown after the standard 3 retries for it have happened? Or are multipart uploads not covered by the retry policy?
I'm using Laravel 5.3 and need to upload an xml file and then submit the contents to an api. The client wants it as 2 buttons/user functions where the user should first upload the file and then with a second click submit the contents.
The uploading is working fine and the xml reading and submitting to api is also working properly. I just can't get my upload controller to pass the filename over to the submitting controller. There is no need to store the filename for future use and the processes will follow each other - ie user will upload one file and submit, then upload next file and submit.
Any help would be highly appreciated
upload function:
public function handleUpload(Request $request)
{
$file = $request->file('file');
$allowedFileTypes = config('app.allowedFileTypes');
$rules = [
'file' => 'required|mimes:'.$allowedFileTypes
];
$this->validate($request, $rules);
$fileName = $file->getClientOriginalName();
$destinationPath = config('app.fileDestinationPath').'/'.$fileName;
$uploaded = Storage::put($destinationPath, file_get_contents($file->getRealPath()));
if($uploaded) {
$file_Name = ($_FILES['file']['name']);
}
return redirect()->to('/upload');
}
submit function:
public function vendorInvoice()
{
$fileName = $file_Name;
$destinationPath = storage_path('app/uploads/');
$xml = file_get_contents($destinationPath.$fileName);
$uri = "some uri";
try {
$client = new Client();
$request = new Request('POST', $uri, [
'Authorization' => '$username',
'ContractID' => '$id',
'content-type' => 'application/xml'
],
$xml);
$response = $client->send($request);
}
catch (RequestException $re) {
//Exception Handling
echo $re;
}
}
I am synchronizing a Centos directory of MP3's with a Dropbox shared folder. When I copy MP3 files into the folder in Windows all is well. When I upload from Centos using a PHP script and the REST interface the files arrive, but they're a larger size and are missing the tags. I can still play the files so it's not simple file corruption. I'm opening the file in binary mode in the PHP script. Here's the relevant code:
$path = $this->dropboxPath($root, $subDir, $fileName);
$uri = "https://api-content.dropbox.com/1/files_put/auto/$path";
$lclPath = storage_path() . "/$root/$subDir/$fileName";
$fd = fopen($lclPath, 'rb');
$this->putDropbox($uri, [
'overwrite' => 'true'
], $fd
);
private function putDropbox($uri, $parms, $fd) {
$uri = $uri . "?" . http_build_query($parms);
$client = new GuzzleHttp\Client();
$req = $client->createRequest('PUT', $uri, [
'exceptions' => true,
'body' => [
'file_filed' => $fd
]
]);
$req->setHeader('Authorization', 'Bearer ' . $this->token);
try {
$resp = $client->send($req);
return $resp;
}
catch(Exception $e) {
Log::error($e->getRequest());
if($e->hasResponse()) {
Log::error($e->getResponse());
}
}
}
I found mediafire API few days ago.
http://developers.mediafire.com
and I search over the internet is there anyway to make a web app for upload files to mediafire account using API. Unfortunately I haven't found anything. Is anybody know how to create a file uploading web app with mediafire API and PHP.
First get a session token.
$apikey = 'YOUR API KEY HERE';
$appid = 'APPLICATIONID';
$email = 'your#email.com';
$passwd = 'PASSWORD';
$params = http_build_query(array(
'email' => $email,
'password'=> $passwd,
'application_id' => $appid,
'signature' => sha1("$email$passwd$appid$apikey"),
'response_format' => 'json'
));
$fp = fopen('https://www.mediafire.com/api/user/get_session_token.php?'.$params, 'r');
$json = stream_get_contents($fp);
$obj = json_decode($json);
fclose($fp);
$session = $obj->response->session_token;
Now with this new $session key upload a file.
$filecontents = file_get_contents("/path/to/file");
$filesize = strlen($filecontents);
$opts = array(
'http'=>array(
'method'=>"POST",
'header'=> "x-filename : ANYFILENAMEYOUWANT\r\n".
"x-filesize : $filesize\r\n"
)
);
$context = stream_context_create($opts);
$params = http_build_query(array(
"session_token" => $session
));
$fp = fopen('http://www.mediafire.com/api/upload/upload.php?'.$params, 'r', false, $context);
fwrite($fp, $filecontents);
$result = stream_get_contents($fp);
fclose($fp);
Important Note: Please try it yourself. I have not tested it. Just saw the API and wrote this code. So it wont work on first go. You'll need to modify to make it work.