shows me blank page when upload a .docx document on a website laravel - laravel-5

Hello I am new to laravel and still learning it and I come across different problems and issues and I cant find a way to solve it. I have been stuck to this since very long. Any help would be much appreciated.
The Problem
Whenever I upload a .docx file to my website i get a blank page without any error or without the content of that docx file. I dont know what the problem is. Please help me out with this.
Code
public function getUploadedFile() {
// $destinationPath = 'uploads';
// $path= public_path()."/". $destinationPath;
// $content = utf8_encode(File::get('/var/www/html/asad/File-Uploader/public/uploads/detailed_period_report_template.xls'));
// return view('/files', compact('path'));
$file = $this->request->file('file_name');
$file_name = $this->request->file_name;
if (File::isFile($file_name))
{
$file_name = File::get($file_name);
$response = Response::make($file_name, 200);
$content_types = [
'application/octet-stream', // txt etc
'application/msword', // doc
'application/vnd.openxmlformats-officedocument.wordprocessingml.document', //docx
'application/vnd.ms-excel', // xls
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // xlsx
'application/pdf', // pdf
];
// using this will allow you to do some checks on it (if pdf/docx/doc/xls/xlsx)
$response->header('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
return $response;
}
I dont have any view for this. Do I need one for this ? If yes what would be it like because every docx file has it's set of properties like font, size, etc unlike excel sheets where we just defines columns. Please help me out. Thank you in advance

I have figured it out after so long finally.
It was sending "null" as a file name so what I did now is got the file name from the database instead of storage and then compared it that if that file is in storage and database then open it. Below is the code running for me now.
Thank you #MATEY for all your help though
$upload = new Upload;
$file= public_path(). "/uploads/" . $upload->file_name = $this->request->file_name;
//dd($file);
$files = File::get($file);
$response = Response::make($files, 200);
and changed the content type to $response->header('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
Thank you for the all help #MATEY. You gave me the motivation to fix it plus your else{...} part missing in if condition actually helped me alot finding out the error.

Related

DOMPDF: How to customize the name of the single pdf, relating to a single client, with the information present in the object

I am trying to create the pdf, using the domPDF library, for each single client present in the table of my application. So far everything ok!
When I go to save the pdf I want the name of the pdf document to be saved as:
name_client_surname_client.pdf,
so if for example I have a client named Alex Haiold, the document must be saved as Alex_Haiold.pdf
To do this, since I am passing the single client in the controller, as shown below, I tried to write
return $pdf->download('client->surname client->name.pdf');
but it is saved as
client-_surname client-_name.pdf (then printing client-_surname client-_name).
Here my code:
public function generatePDF(Client $client)
{
$data = [
'title' => 'Welcome to LaravelTuts.com',
'date' => date('m/d/Y'),
'client' => $client
];
//dd($data);
$pdf = PDF::loadView('client.clientPDF', $data);
return $pdf->download('client->surname client->name.pdf');
}
Can anyone kindly help me?
$pdf = PDF::loadView('client.clientPDF', $data);
return $pdf->download($client->surname . ' ' . client->name . '.pdf');
On the first line, we are just making a view file. The file is resources/views/client.clientPDF.blade.php and we are feeding data to the view file by passing the variable $data to it.
After making the view, our next step is to download the pdf file. For doing this, we need to call the download method of the instance.
On the first parameter, we are passing the filename with extension(pdf).

PDF not generated in laravel

I'm generating pdf using following code in Laravel but the issue is sometimes data is saved in the database and pdf is not generated when i check the pdf folder there is no pdf files with that name, this does not happens every time i generate the pdf but there are some entries in my database for which the pdf is not generated, i want some way so that i can check whether the pdf has been generated and mark status true in the database if pdf is generated later on recreate pdf and send it to user through cron jobs or is there any other way also, Please suggest some solution Thanks
use PDF;
..
..
$DataStore->user_id = $user_id;
$DataStore->description = $description;
$DataStore->save();
if($DataStore) {
$pdf = PDF::loadView('/admin/user_submission_pdf', ['data' => $DataStore]);
$content = $pdf->download()->getOriginalContent();
Storage::put('public/pdfFiles/' . $DataStore->Id . '.pdf', $content);
to download your pdf, change the the line
$content = $pdf->download()->getOriginalContent();
to
$content = $pdf->download('file-name-you-want.pdf');
then at last line should return:
return $content;

Laravel : To rename an uploaded file automatically

I am allowing users to upload any kind of file on my page, but there might be a clash in names of files. So, I want to rename the file automatically, so that anytime any file gets uploaded, in the database and in the folder after upload, the name of the file gets changed also when other user downloads the same file, renamed file will get downloaded.
I tried:
if (Input::hasFile('file')){
echo "Uploaded</br>";
$file = Input::file('file');
$file ->move('uploads');
$fileName = Input::get('rename_to');
}
But, the name gets changed to something like:
php5DEB.php
phpCFEC.php
What can I do to maintain the file in the same type and format and just change its name?
I also want to know how can I show the recently uploaded file on the page and make other users download it??
For unique file Name saving
In 5.3 (best for me because use md5_file hashname in Illuminate\Http\UploadedFile):
public function saveFile(Request $request) {
$file = $request->file('your_input_name')->store('your_path','your_disk');
}
In 5.4 (use not unique Str::random(40) hashname in Illuminate\Http\UploadedFile). I Use this code to ensure unique name:
public function saveFile(Request $request) {
$md5Name = md5_file($request->file('your_input_name')->getRealPath());
$guessExtension = $request->file('your_input_name')->guessExtension();
$file = $request->file('your_input_name')->storeAs('your_path', $md5Name.'.'.$guessExtension ,'your_disk');
}
Use this one
$file->move($destinationPath, $fileName);
You can use php core function rename(oldname,newName) http://php.net/manual/en/function.rename.php
Find this tutorial helpful.
file uploads 101
Everything you need to know about file upload is there.
-- Edit --
I modified my answer as below after valuable input from #cpburnz and #Moinuddin Quadri. Thanks guys.
First your storage driver should look like this in /your-app/config/filesystems.php
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'), // hence /your-app/storage/app/public
'visibility' => 'public',
],
You can use other file drivers like s3 but for my example I'm working on local driver.
In your Controller you do the following.
$file = request()->file('file'); // Get the file from request
$yourModel->create([
'file' => $file->store('my_files', 'public'),
]);
Your file get uploaded to /your-app/storage/app/public/my_files/ and you can access the uploaded file like
asset('storage/'.$yourModel->image)
Make sure you do
php artisan storage:link
to generate a simlink in your /your-app/public/ that points to /your-app/storage/app/public so you could access your files publicly. More info on filesystem - the public disk.
By this approach you could persists the same file name as that is uploaded. And the great thing is Laravel generates an unique name for the file so there could be no duplicates.
To answer the second part of your question that is to show recently uploaded files, as you persist a reference for the file in the database, you could access them by your database record and make it ->orderBy('id', 'DESC');. You could use whatever your logic is and order by descending order.
You can rename your uploaded file as you want . you can use either move or storeAs method with appropiate param.
$destinationPath = 'uploads';
$file = $request->file('product_image');
foreach($file as $singleFile){
$original_name = strtolower(trim($singleFile->getClientOriginalName()));
$file_name = time().rand(100,999).$original_name;
// use one of following
// $singleFile->move($destinationPath,$file_name); public folder
// $singleFile->storeAs('product',$file_name); storage folder
$fileArray[] = $file_name;
}
print_r($fileArray);
correct usage.
$fileName = Input::get('rename_to');
Input::file('photo')->move($destinationPath, $fileName);
at the top after namespace
use Storage;
Just do something like this ....
// read files
$excel = $request->file('file');
// rename file
$excelName = time().$excel->getClientOriginalName();
// rename to anything
$excelName = substr($excelName, strpos($excelName, '.c'));
$excelName = 'Catss_NSE_'.date("M_D_Y_h:i_a_").$excelName;
$excel->move(public_path('equities'),$excelName);
This guy collect the extension only:
$excelName = substr($excelName, strpos($excelName, '.c'));
This guy rename its:
$excelName = 'Catss_NSE_'.date("M_D_Y_h:i_a_").$excelName;

return file response in laravel not working

I'm using laravel 5.2 , I've used response()->file() function to return file. On localhost it is working as expected but on live server file is being downloaded automatically (with no extension). But i wish to open it instead of downlod. Anyone can help?
Here is my code:
public function returnFile($slug)
{$file = Mixes::where('id_name,'=',$slug)->get()->first();
return response()->file('./path/to/file/'.$file->name);}
Thanks.
You'll need to add header to your response.
Response with header example:
$response->header('Content-Type', 'application/pdf');
Simple example:
$file = File::get($file);
$response = Response::make($file, 200);
$response->header('Content-Type', 'application/pdf');
return $response;
Then the file will display in your browser window.
This solution will work with files pdf,docx,doc,xls.
Hope it will help!

Laravel 4 get image from url

OK so when I want to upload an image. I usually do something like:
$file = Input::file('image');
$destinationPath = 'whereEver';
$filename = $file->getClientOriginalName();
$uploadSuccess = Input::file('image')->move($destinationPath, $filename);
if( $uploadSuccess ) {
// save the url
}
This works fine when the user uploads the image. But how do I save an image from an URL???
If I try something like:
$url = 'http://www.whereEver.com/some/image';
$file = file_get_contents($url);
and then:
$filename = $file->getClientOriginalName();
$uploadSuccess = Input::file('image')->move($destinationPath, $filename);
I get the following error:
Call to a member function move() on a non-object
So, how do I upload an image from a URL with laravel 4??
Amy help greatly appreciated.
I don't know if this will help you a lot but you might want to look at the Intervention Library. It's originally intended to be used as an image manipulation library but it provides saving image from url:
$image = Image::make('http://someurl.com/image.jpg')->save('/path/saveAsImageName.jpg');
$url = "http://example.com/123.jpg";
$url_arr = explode ('/', $url);
$ct = count($url_arr);
$name = $url_arr[$ct-1];
$name_div = explode('.', $name);
$ct_dot = count($name_div);
$img_type = $name_div[$ct_dot -1];
$destinationPath = public_path().'/img/'.$name;
file_put_contents($destinationPath, file_get_contents($url));
this will save the image to your /public/img, filename will be the original file name which is 123.jpg for the above case.
the get image name referred from here
Laravel's Input::file method is only used when you upload files by POST request I think. The error you get is because file_get_contents doesn't return you laravel's class. And you don't have to use move() method or it's analog, because the file you get from url isn't uploaded to your tmp folder.
Instead, I think you should use PHP upload an image file through url what is described here.
Like:
// Your file
$file = 'http://....';
// Open the file to get existing content
$data = file_get_contents($file);
// New file
$new = '/var/www/uploads/';
// Write the contents back to a new file
file_put_contents($new, $data);
I can't check it right now but it seems like not a bad solution. Just get data from url and then save it whereever you want

Resources