PDF preview refused to connect using PHP Laravel - php

I'm making some kind of form be able to upload PDF file. And I also make a label to preview the file that I'm uploading. But somehow the label wont preview the file with error massage : refused to connect. Can somebody help me with it?
image form preview
So here's the PHP code for the label on the view file that I use :
<div class="form-group row">
<label class="col-md-2 col-form-label">File</label>
<div class="col-md-6">
<input type="file" name="file" id="file" class="form-control" required>
<iframe src="{{ $data['data']['files'] }}" style="width: 1000px; height:500px;" frameborder="0" id="filePreview" class="mt-2"></iframe>
</div>
<small class="text-small">{{ $errors->first('file') }}</small>
</div>
And here is the edit and update controller that I use for that view
public function edit($id)
{
$system = new SystemService();
$systemData = $system->list_badges();
$data['system'] = $systemData['data'];
$api = new SettingService();
$data['data'] = $api->get_about($id);
$data['title'] = 'Ubah Tentang Aplikasi';
$data['default'] = $this->folder;
$data['data_view'] = $this->folder . '/edit';
return view('template', $data);
}
public function update(Request $request, $id)
{
$api = new SettingService();
if ($request->hasFile('file')) {
$file = $request->file('file');
$mime = $file->getClientOriginalExtension();
$filter_file = [
'pdf',
'doc', 'docx',
'csv', 'xls', 'xlsx',
'png', 'jpg', 'jpeg',
];
if (!in_array($mime, $filter_file)) {
return back()->with('failed', 'file extention not correct');
}
$file_path = $request->file('file')->path();
$file_name = md5(date('YmdHis') . $file->getClientOriginalName()) . '.' . $file->getClientOriginalExtension();
$data['file_path'] = $file_path;
$data['file_name'] = $file_name;
}
$result = $api->update_about($id, $data);
if (isset($result['errors'])) {
return redirect($this->folder . '/' . $id . '/edit')->withErrors($result['errors'])->withInput()->with('failed', $result['message']);
}
if ($result['status'] == false) {
return redirect($this->folder . '/' . $id . '/edit')->withInput()->with('failed', $result['message']);
}
return redirect($this->folder)->with('success', $result['message']);
}
Thankyou

Related

Multiple image upload in laravel

i have this code in my controller that can make me upload successfully just one file , and i want to upload many files in once time :
public function store(Request $request, $id) {
$request->validate([
'image' => 'required',
]);
$listing = Listing::findOrFail($id);
$image = new Listingimage();
if ($request->hasFile('image')) {
$file = $request->file('image');
$extention = $file->getClientOriginalExtension();
$filename = time() . '.' . $extention;
$file->move('assets/images/listingimages/', $filename);
$fileOriginalName = $file->getClientOriginalName();
}
$image->listing_id = $id;
$image->image_url = $filename;
$image->nom_image = $fileOriginalName;
$image->save();
return redirect()->back();
}
i use also this input :
<form action="{{ route('Listingimages.store', $listing->id) }}" method="POST" enctype="multipart/form-data">
<input type="hidden" name="_method" value="PUT" />
{{csrf_field()}}
{{method_field('PUT')}}
<label> Insert image</label>
<input type="file" name="image" id="files" class="form-control" multiple>
so , how can i upload many files in once time ?
change input name
<input type="file" name="image[]" id="files" class="form-control">
controller
public function store(Request $request, $id) {
$request->validate([
'image' => 'required',
]);
$listing = Listing::findOrFail($id);
if ($request->hasFile('image')) {
foreach($request->file('image') as $file)
{
$image = new Listingimage();
$file = $request->file('image');
$extention = $file->getClientOriginalExtension();
$filename = time() . '.' . $extention;
$file->move('assets/images/listingimages/', $filename);
$fileOriginalName = $file->getClientOriginalName();
$image->listing_id = $id;
$image->image_url = $filename;
$image->nom_image = $fileOriginalName;
$image->save();
}
}
return redirect()->back();
}

Upload an image and file to forum

I have searched for the SO and didn't find any article or post related to this.
How do I upload an Image using the Image Intervention and upload a normal file with in a single forum without opening a new page for the uploads.
Hope the below Answer would help someone out there.
Blade
<form action="{{route('index.store')}}" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label for="resume_path">Resume</label>
<input type="file" class="form-control"
name="resume_path">
</div>
<div class="form-group">
<label for="engineer_avatar">Profile Image</label>
<input type="file" class="form-control"
name="engineer_avatar">
</div>
</form>
Controller
use Image;
use App\Engineers;
*/
public function update(Request $request, $id)
{
$this->validate($request,[
'engineer_avatar' => 'image|mimes:jpeg,png,jpg|max:2048',
'resume_path' => 'file|mimes:doc,docx,pdf|max:2048',
// dimensions:min_width=600,min_height=400'
]);
$engineers = Engineers::findOrFail($id);
if($request->hasFile('engineer_avatar')){
$image = $request->file('engineer_avatar');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/engineer_avatar/' . $filename);
Image::make($image)->resize(600,400)->save($location);
$engineers->avatar_path = $filename;
}
if($request->hasFile('resume_path')){
$file = $request->file('resume_path');
$file_name1 = time() . '.' . $file->getClientOriginalExtension();
$file_path = public_path('resume/engineer/');
$engineers->resume_path = $file_name1;
$file->move($file_path, $file_name1);
$engineers->save();
}
To delete the file ::
public function destroy($id)
{
$engineers = Engineers::findOrFail($id);
unlink(public_path('images/engineer_avatar/' . $engineers->avatar_path ));
unlink(public_path('resume/engineer/' . $engineers->resume_path ));
$engineers->delete();
}

Multiple resize image upload with Laravel

I'm working to make a multi upload image to database with intervention resizer in Laravel.
This is what I'm coding right now in my controller
imgProdukProc controller:
use Illuminate\Http\Request;
use File;
use Image;
use App\imgProd;
.....
public function store(Request $request)
{
if($request->hasFile('img')){
foreach ($request->file('img') as $image) {
if ($image->isValid()) {
$img = new imgProd();
$image_name = uniqid() .'.'. $image->getClientOriginalExtension();
$path = public_path('/img/prod');
$imgx = Image::make($image->getRealPath());
$imgx->resize(360, 360, function ($constraint) {
$constraint->aspectRatio();
})->save($path.'/'.$image_name);
$img->id_prod = $request->get('id_prod');
$img->pics = 'img/prod/'.$image_name;
$date=date_create('now');
$format = date_format($date,"Y-m-d");
$img->date = $format;
$img->save();
return redirect('adminImgProd')->with('success', 'Picture successfully added ');
}
}
}
}
and this is my views
adminImgProd Views
<form enctype="multipart/form-data" action="{{url('adminImgProd')}}" method='post'>
#csrf
<div class="form-group">
<label>CODE PRODUCT</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-pencil"></span></span>
<input type="text" autocomplete="off" class="form-control" id='id_prod' name='id_prod' required="required" />
<span class="input-group-addon"><button type="button" onClick="javascript:openWindow2();">Select</button></span>
</div>
</div>
<div class="form-group">
<label>IMAGE PRODUCT</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-pencil"></span></span>
<input multiple type="file" class="form-control" name='img[]' id='file-input' required="required" /></div>
</div>
Code above is working , but somehow when I tried to upload 2 images or 3 images the only image saved both in target folder and in database is only one and it is the last one
Where is my code mistake , or just my code simply wrong from the start ?
Thank you in advance
You put your return in your foreach, so after 1 loop, it will return and exit your function :
public function store(Request $request)
{
if ($request->hasFile('img')){
foreach ($request->file('img') as $image) {
if ($image->isValid()) {
$img = new imgProd();
$image_name = uniqid() .'.'. $image->getClientOriginalExtension();
$path = public_path('/img/prod');
$imgx = Image::make($image->getRealPath());
$imgx->resize(360, 360, function ($constraint) {
$constraint->aspectRatio();
})->save($path.'/'.$image_name);
$img->id_prod = $request->get('id_prod');
$img->pics = 'img/prod/'.$image_name;
$date=date_create('now');
$format = date_format($date,"Y-m-d");
$img->date = $format;
$img->save();
}
}
return redirect('adminImgProd')->with('success', 'Picture successfully added ');
}
}
You can do the following for multiple images:
$images = $request->file('images');
foreach ($images as $key => $image) {
if ($request->hasFile('images') && $request->file('images')[$key]->isValid()) {
$path = $request->images[$key]->store('public/images');
$path = basename($path);
$image = new ProductImages();
$image->product_id = $request->get('product_id');
$image->photo = $path;
$image->save();
}
}
I hope it would helpful.

Unable to change Profile Picture Laravel

I am able to store the image in desired location but I am unable to view it.
When the page is reloaded ,the same default image appears .
Default image never changes to my desired Image.
My Controller File(UserController.php):
public function update_avatar(Request $request)
{
if($request->hasFile('avatar'))
{
$avatar = $request->file('avatar');
$filename = time(). '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->save(public_path('/src/uploads/avatars/' . $filename));
}
return redirect()->route('dashboard');
}
}
My Route file:
Route::post('/dashboard',[
'uses'=>'UserController#update_avatar',
]);
My view File:
<form action="/dashboard" method="post" enctype="multipart/form-data">
<div id="mySidenav" class="sidenav">
×
<input type="file" name="avatar" class="btn btn-sm btn-primary col-md-5" >
<input type="submit" class="pull-right btn btn-sm btn-primary " value="submit">
<input type="hidden" value="{{Session::token() }}" name="_token">
Remove
</div>
<div id="main">
<span style="font-size:30px;cursor:pointer" onclick="openNav()"><img src="download.jpg" class="img-circle img-responsive" alt="Placeholder image"></span>
</div>
</form>
Are you not saving the uploaded Image to the Database? Are you only uploading images to the dedicated Images Folder but not saving it to the Database? If you want, you can do this in your controller:
<?php
public function update_avatar(Request $request){
$avatarURI = null;
if($request->hasFile('avatar')) {
$avatar = $request->file('avatar');
$filename = time(). '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->save(public_path('/src/uploads/avatars/' . $filename));
$avatarURI = "src/uploads/{$filename}";
User::update();
}
// YOU MAY NEED TO PERSIST THIS IN THE DATABASE
// TO UPDATE THE avatar:
$usr = new \App\User();
$usr->update(['avatar' => $avatarURI, 'id'=>$userID]); //<== ID OF THE USER TO BE UPDATED...
return redirect()->route('dashboard', ['imgURI'=>$avatarURI, 'user'=>$usr]);
}
Change user with avatar attribute suit your need
public function update_avatar(Request $request)
{
if($request->hasFile('avatar'))
{
$avatar = $request->file('avatar');
$path = '/src/uploads/avatars/';
$filename = time(). '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->save(public_path($path . $filename));
$request->user()->avatar = $filename;
$request->user()->save();
}
return redirect()->route('dashboard');
}

store uploaded file path to database mysql and download it

I am using codeigniter and now I want to upload the file path to the table.
This code below only storing the folder path, like '
http://localhost/kirimundangan.com/kirim_undangan/' not the actual file name. I expected like 'http://localhost/kirimundangan.com/kirim_undangan/somefile.xlsx'.
Function upload when user upload file via dropzone:
function upload()
{
$this->load->library('session');
if (!empty($_FILES))
{
$filename = $_FILES["file"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$tempFile = $_FILES['file']['tmp_name'];
$data = uniqid(). $file_ext;
$targetPath = getcwd() . '/kirim_undangan/';
$targetFile = $targetPath . $data ;
move_uploaded_file($tempFile, $targetFile);
$_SESSION["xls"] = $data;
print_r($_SESSION['xls']);
}
Function undangan when user submit input text along with the uploaded file :
function undangan()
{$email = $this->input->post('email');
$from_nama = $this->input->post('from_nama');
$from_phone = $this->input->post('from_phone');
$filename = $_FILES["file"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$tempFile = $_FILES['file']['tmp_name'];
$data_file = uniqid(). $file_ext;
$targetPath = getcwd() . '/kirim_undangan/';
$targetFile = $targetPath . $data ;
$data_user = array(
'email' => $email,
'name' => $from_nama,
'phone' => $from_phone,
'status' => '0',
'filename_user' => site_url('/kirim_undangan/.uniqid()'),
);
$this->load->model('excel');
$this->excel->tambahuser($data_user);
The model :
function tambahuser($data_user)
{
$this->db->insert('request', $data_user);
$this->db->insert_id();
foreach ($data_user as $key)
{
$data = array(
'from_name' => $this->input->post('from_nama'),
'from_phone' => $this->input->post('from_phone')
);
}
}
And the view :
<div class="modal-body">
<div id="form_pesan">
<div action="<?php echo site_url('/kirim/upload'); ?>" class="dropzone" id="dropzone_form">
<div class="dz-message" data-dz-message><span><h4>Klik atau drop file Disini
</h4></span></div>
</div>
<div class="row" id="form_user" style="display: none;">
<h4 id="form">Data Personal</h4>
<div class="col-sm-4">
<input type="email" class="form-control input-lg" id="email" name="email" placeholder="Email" required>
</div>
<div class="col-sm-4">
<input type="text" class="form-control input-lg" id="from_nama" name="from_nama" placeholder="Nama" required>
</div>
<div class="col-sm-4">
<input type="number" class="form-control input-lg" id="from_phone" name="from_phone" placeholder="Phone" required>
</div>
<div>
<input type="hidden" name="id" id="id" />
</div>
<br>
<div class="row" align="center">
<button id="pesan" type="button" class="btn btn-download btn-md" onclick=pesan()>
<span class="glyphicon glyphicon-send" aria-hidden="true" ></span>Pesan
</button>
</div>
</div>
If the path is store into table, I will use it to download the file. Btw, is storing a file path into database is better practice than storing the actual file? (I need to store a xls or doc file)
my form :
javascript :
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone('#dropzone_form',{
acceptedFiles: ".xlsx, .xls, .docs, .doc, .pdf" ,
"maxFiles":1 ,
init: function () {
var thisDropzone = this;
this.on("success", function(files, response) {
$('#alert_drpzone').show();
$('#form_user').show();
$('#dropzone_form').hide();
$('#myModalLabel').hide();
});
this.on("error", function(files,response) {
$('#alert2').show();
})
}
});
function pesan()
{
email = $("#email").val();
from_nama = $("#from_nama").val();
from_phone = $("#from_phone").val();
$.ajax
({
url : "<?php echo site_url('kirim/undangan')?>/",
type: "POST",
dataType: "text",
data:{from_nama: from_nama, email: email, from_phone: from_phone},
success: function(data)
{
$('#alert_sukses').show();
$('#form_pesan').hide();
$('#myModalLabel').hide();
$('#email'+data).html(data.email);
$('#from_nama'+data).html(data.from_nama);
$('#from_phone'+data).html(data.from_phone);
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error upload data');
}
});
}
You didn't call the upload() in undangan(). In upload() return $targetFile so that it will give you the uploaded file name then add that name into $data_user.
function upload()
{
if (!empty($_FILES))
{
$filename = $_FILES["file"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$tempFile = $_FILES['file']['tmp_name'];
$data = uniqid(). $file_ext;
$targetPath = getcwd() . '/kirim_undangan/';
$targetFile = $targetPath . $data ;
move_uploaded_file($tempFile, $targetFile);
return $targetFile; //return uploaded file name with directory
}
change controller like
function undangan()
{
$email = $this->input->post('email');
$from_nama = $this->input->post('from_nama');
$from_phone = $this->input->post('from_phone');
$uploadedFileName = $this->upload();
$data_user = array(
'email' => $email,
'name' => $from_nama,
'phone' => $from_phone,
'status' => '0',
'filename_user' => $uploadedFileName,
);
$this->load->model('excel');
$this->excel->tambahuser($data_user);
}
Hope this will solve your problem. If you need any help. Im happy to guide you

Categories