I am able to upload jpg and pdf to my server (database). Now, I want to be able to download it when I click on the file itself in my view as shown below.
When I click on the file, it routes me to the download page and says page cannot be found and the file is not downloaded
What am I not doing right?
Controller
public function upload(Request $request)
{
$storeFiles = new File;
$uniqueFileName = uniqid() . Input::file('upload_file')->getClientOriginalName() . '.' . Input::file('upload_file')->getClientOriginalExtension();
Input::file('upload_file')->move(public_path('/public/files') . $uniqueFileName);
$storeFiles->path = $uniqueFileName;
$storeFiles->description = Input::get('description');
$storeFiles->save();
return redirect()->back()->with('status', 'File uploaded successfully.');
}
public function download($filename)
{
$file_path = public_path('/public/files'). $filename;
if (file_exists($file_path))
{
// Send Download
return Response::download($file_path, $filename, [
'Content-Length: '. filesize($file_path)
]);
}
else
{
// Error
exit('Requested file does not exist on our server!');
}
}
Routes
Route::get('/course/download/{{file?}}', 'FileController#download')->name('course.download');
View
<td>{{$file->path}}</td>
Related
I testing a code for upload image on laravel 5.8 local and I uploaded image unsuccessful then I recieved error 403 forbidden.
public function store(Request $request)
{
request()->validate([
'profile_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($files = $request->file('profile_image')) {
// Define upload path
$destinationPath = public_path('/profile_images/'); // upload path
// Upload Orginal Image
$profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profileImage);
$insert['image'] = "$profileImage";
// Save In Database
$imagemodel= new Photo();
$imagemodel->photo_name="$profileImage";
$imagemodel->save();
}
return back()->with('success', 'Image Upload successfully');
}
I followed above code on internet and I don't know where I wrong. I need help !
Thank you.
Have you tried php artisan storage:link
Try this code format just change variable name
Try this on your project folder
chmod -R 777
$request->validate([
'profile_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$fileNameWithExt = $request->file('profile_image')->getClientOriginalName();
$ext = $request->file('profile_image')->getClientOriginalExtension();
$fileNameWithoutExt = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$fileNameToStore = $fileNameWithoutExt . time() . "." . $ext;
$path = $request->file('profile_image')->storeAs('public/profile_images', $fileNameToStore);
$addPhoto = Photo::create([
'photo_name' => $fileNameToStore,
]);
if ($addPhoto) {
return back()->with('success', 'Image Upload successfully');
}
yesterday I tried to find on internet but it's seem not result for my situation, so I try to replace $uri in route and it work,
I change from:
Route::get('images','ImagesController#index')->name('image.index');
to:
Route::get('imageproduct','ImagesController#index')->name('image.index');
but I still don't know why does error appear and how to fix it.
And I also check image link on database, it's seem not save to database, can you give me suggest about upload image . Thank You
I'm trying to upload an images using method moving the temporary files, and show it on my index page only with the path.
Here's the problem:
ErrorException in ProductController.php line 69: Trying to get property of non-object
In my controller that contain the line who error:
public function store(Request $request)
{
$product=Request::all();
Product::create($product);
$imageName = $product->id_prod . '.' .
$request->file('images')->getClientOriginalExtension();
$request->file('images')->move(
base_path() . '/public/images/catalog/', $imageName
);
return redirect('product');
}
And here's the database, the file has been uploaded on temp folder, but the file was fail to moved. I'm using Laravel 5.2, it was my first time to upload a files. And can someone explain to me why this one could be error.
Sorry for my bad grammars.
You can try like this:
public function store(Request $request)
{
$product = $request->all();
$picture = '';
if ($request->hasFile('images')) {
$file = $request->file('images');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = $product['id_prod'] . '.' . $extension;
$destinationPath = base_path() . '/public/images/catalog/';
$request->file('images')->move($destinationPath, $picture);
}
if (!empty($product['images'])) {
$product['images'] = $picture;
} else {
unset($product['images']);
}
Product::create($product);
return redirect('/product');
}
I'm trying to implement file transfer using PHP.
I'm getting the following errors:-
Using Html form to upload a file. PHP file to fetch the file using
$_files. How do I get the original file name with extension from the
php object? basename method gives a different name.
I tried uploading a .txt file. It gets converted into php file and gets
uploaded on the server.
On the download part, I'm using ftp_get. I want the file to get
downloaded to my laptop. However it is getting saved on the server
itself with the whole path which i specify in $fileToy. No error
displayed, also file doesn't get downloaded. Here for simplicity
I've given the path directly considering I've uploaded a .txt file.
Please help for general case(any file format).
Here is my code
if ((isset($_FILES['myfile']['tmp_name'])))
$myfile = $_FILES['myfile']['tmp_name'];
else echo "upload not possible";
$fileFrom = $myfile;
$fileTo = 'photos/'. basename($myfile); //photos is directory created on server
echo $fileTo;
$ftpObj -> uploadFile($fileFrom, $fileTo);
$fileFrom = $fileTo ; # The location on the server
$fileToy = 'Downloads\techppr.txt' ; # Local dir to save to
// *** Download file
$ftpObj->downloadFile($fileFrom, $fileToy);
public function uploadFile ($fileFrom, $fileTo)
{
// *** Set the transfer mode
$asciiArray = array('txt', 'csv');
$extension = end(explode('.', $fileFrom));
if (in_array($extension, $asciiArray)) {
$mode = FTP_ASCII;
} else {
$mode = FTP_BINARY;
}
// *** Upload the file
$upload = ftp_put($this->connectionId, $fileTo, $fileFrom, $mode);
}
public function downloadFile ($fileFrom, $fileTo)
{
// *** Set the transfer mode
$asciiArray = array('txt', 'csv');
$extension = end(explode('.', $fileFrom));
if (in_array($extension, $asciiArray)) {
$mode = FTP_ASCII;
} else {
$mode = FTP_BINARY;
}
if (ftp_get($this->connectionId, $fileTo, $fileFrom, $mode, 0)) {
return true;
$this->logMessage(' file "' . $fileTo . '" successfully downloaded');
} else {
return false;
$this->logMessage('There was an error downloading file "' . $fileFrom . '" to "' . $fileTo . '"');
}
}
Here is my code in frontend site controller to update user and i am adding user using backend so i store user images in backend/www/images folder and want to use same path for file upload when i upload user image from frontend
My code in frontend is
public function actionupdateuser()
{
$model = User::model()->findByAttributes(array('memberid' => Yii::app()->user->id));
if (isset($_POST['User']))
{
$rnd = rand(0, 9999); // generate random number between 0-9999
$uploadedFile = CUploadedFile::getInstance($model, 'photo');
$fileName = "{$rnd}-00-{$uploadedFile}"; // random number + file name
$model->attributes = $_POST['User'];
if ($model->validate())
{
if (!empty($uploadedFile))
{
$path = Yii::app()->request->baseUrl . '/../../backend/www/images/';
$uploadedFile->saveAs($path . $fileName);
$model->photo = $fileName;
}
if ($model->save())
$this->redirect(array('useraccountdetail'));
}
else
{
echo 'eroors';
exit;
}
}
$this->render('updateuser', array('model' => $model));
}
Here is the error i got
*move_uploaded_file(/simplifysupper/frontend/www/../../backend/www/images/6086-00-Penguins.jpg): failed to open stream: No such file or directory *
$basePath = str_replace(DIRECTORY_SEPARATOR.'protected', "", str_replace('frontend', '', Yii::app()->basePath));
$uploadDir = 'backend/www/images/';
$uploadedFile->saveAs($basePath .$uploadDir. $fileName);
Hope this helps ;)
You should specify full path to file (now you specify relative path) to file.
$pathToAppRoot = str_replace(DIRECTORY_SEPARATOR.'protected', "", Yii::app()->basePath);
$uploadedFile->saveAs(pathToAppRoot.'/simplifysupper/frontend/www/'.$fileName);
I'm trying to upload images into a Laravel app that will then need to be publicly displayed. However, I seem to only be able to upload to a folder within the application root. Any attempt to upload to the public directory throws the following error:
protected function getTargetFile($directory, $name = null)
{
if (!is_dir($directory)) {
if (false === #mkdir($directory, 0777, true)) {
throw new FileException(sprintf('Unable to create the "%s" directory', $directory));
I'm assuming this means that Laravel is going to prevent me from uploading to any file that is publicly accessible. I actually rather like this, however, how can I link to images that are outside of the public directory I've tried to ../ my way out of the public folder, but appropriately, that didn't work.
Alternately, anything that will let me uploaded directly to the public folder would be great too.
If it helps, here is my controller method that puts the file in public folder:
$thumbnail_file = Input::file('thumbnail');
$destinationPath = '/uploads/'. str_random(8);
$thumbnail_filename = $thumbnail_file->getClientOriginalName();
$uploadSuccess = Input::file('thumbnail_url')->move($destinationPath, $thumbnail_filename);
Route::post('upload', function(){
$avarta = Input::file('avatar');
if(strpos($avarta->getClientMimeType(),'image') !== FALSE){
$upload_folder = '/assets/uploads/';
$file_name = str_random(). '.' . $avarta->getClientOriginalExtension();
$avarta->move(public_path() . $upload_folder, $file_name);
echo URL::asset($upload_folder . $file_name); // get upload file url
return Response::make('Success', 200);
}else{
return Response::make('Avatar must be image', 400); // bad request
}});
will upload to /public/assets/uploads folder, maybe help you
Your destination path should be:
$destinationPath = public_path(sprintf("\\uploads\\%s\\", str_random(8)));
Try using this one in your controller after creating a folder called uploads in your public and another folder called photos in uploads.
$data = Input::all();
$rules = array(
'photo' => 'between:1,5000|upload:image/gif,image/jpg,image/png,image/jpeg',
);
$messages = array(
'upload' => 'The :attribute must be one of the following types .jpg .gif .png .jpeg',
'between' => 'The :attribute file size must be 1kb - 5mb'
);
$validator = Validator::make($data, $rules, $messages);
if($validator->passes())
{
$uploads = public_path() . '/uploads/photos';
$photo = Input::file('photo');
$photodestinationPath = $uploads;
$photoname = null;
if($photo != null)
{
$photoname = $photo->getClientOriginalName();
Input::file('photo')->move($photodestinationPath, $photoname);
}
$thumbnail = new Model_name();
$thumbnail ->column_name_in_table = $photoname;
and then put this in your routes
Validator::extend('upload', function($attribute,$value, $parameters){
$count = 0;
for($i = 0; $i < count($parameters); $i++)
{
if($value->getMimeType() == $parameters[$i])
{
$count++;
}
}
if($count !=0)
{
return true;
}
return false;});
In the ImageProductController.php (Controller) file insert the following code:
public function store(Request $request, $id)
{
if ($request->hasFile('image')){
$rules = [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg'
];
$this->validate($request, $rules);
// Save file in directory
$file = $request->file('image');
$path = public_path() . '/images';
$fileName = md5(rand(0,9999)).'.'.$file->getClientOriginalExtension();
$file->move($path, $fileName);
$imageProduct = new ImageProduct();
$imageProduct->image = $fileName;
}
In the file create.blade.php (View) insert the following code:
<form enctype="multipart/form-data" method="post" action=" " >
{{ csrf_field() }}
<label for="image" class="btn btn-primary">Inserir Imagem</label>
<input type="file" name="image" id="image" accept="image/*"
class="form-control" value="{{ old('image') }}>
</form>
In the ImageProduct.php file (Model) insert the following code:
public function getUrlAttribute()
{
if(substr($this->image, 0, 4) === "http"){
return $this->image;
}
return '/images/'.$this->image;
}
Good luck!
You need to give permission the laravel folder where you want to store images.
The commend is:
sudo chown www-data:www-data /var/www/html/project-name/path/to/folder.