How to upload a file in Laravel? - html

Here is the code to upload an image to the database.
public function create(Request $request)
{
$this->validate($request, [
'comment' => 'required',
]);
$mess = new messageUser;
$mess->user_id = Auth::guard('userLogin')->user()->id;
$mess->message = $request->comment;
if($request->hasFile('image')){
$filenameWithExtention = $request->file('image')->getClientOriginalName();
$fileName = pathinfo($filenameWithExtention,PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameStore = $fileName .'_'.time().'.'.$extension;
$path = $request->image->storeAs('images', $fileNameStore);
$mess->attach = $fileNameStore;
}
$mess->save();
return $mess;
}
Blade
<div class="form-group">
<textarea id="compose-textarea" name="comment"></textarea>
</div>
<div class="form-group">
<div class="input-group">
<input type="file" name="image" class="form-control inputFileVisible" placeholder="attach one file">
<button type="button" class="btn btn-fab btn-round btn-info"><i class="material-icons">attach an image</i>
</button>
</div>
</div>
<button type="submit" class="btn btn-primary"><i class="fa fa-envelope-o"></i>send image</button>
The code sends the message successfully but didn't upload the image.

You can do something like this:
if($request->hasFile('image')){
$filenameWithExtention = $request->file('image')->getClientOriginalName();
$fileName = pathinfo($filenameWithExtention,PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameStore = $fileName .'_'.time().'.'.$extension;
$path = $request->photo->storeAs('images', $fileNameStore);
$mess->attach = $fileNameStore;
}
For more Visit this
Thanks.
Note: Don't forget to run php artisan storage:link

What is the error show us please it will be better to guide you... BTW you ca use following code to uplaod an image/file
if ($request->image) {
$file = $request->File('image');
$ext = $student->username . "." . $file-
>clientExtension();
$file->storeAs('images/', $ext);
$student->image = $ext;
}

Related

Upload multiple forms no save in mysql database laravel 9

could someone help me to find the error? only the post_image input is saved the others are not saved in the database what am I doing wrong?
I've checked it several times but only the filename of the post_image field is saved in the database, the other files are not persisting in the database, could someone help me where I'm going wrong?
Every help is welcome.
Thank you very much in advance.
create.blade.php
div class="form-group row">
<label for="post_image" class="col-md-4 col-form-label text-md-right">{{ __('Image') }}</label>
<div class="col-md-6">
<input type="file" name="post_image"/>
#error('post_image')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<br>
<hr>
<label for="post_video" class="col-md-4 col-form-label text-md-right">{{ __('Video') }}</label>
<div class="col-md-6">
<input type="file" name="post_video"/>
#error('post_video')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<br>
<hr>
<label for="post_gif" class="col-md-4 col-form-label text-md-right">{{ __('GIF') }}</label>
<div class="col-md-6">
<input type="file" name="post_gif"/>
#error('post_gif')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<br>
<hr>
</div>
function store in controller -->
public function store(Request $request, Community $community)
{
$user = Auth::user();
$creds = $request->validate([
'post_image' => '|image|mimes:jpeg,jpg,png,svg|max:18048',
'post_video' => 'mimes:mp4,ogx,oga,ogv,ogg,webm|max:180048',
'post_gif' => '|image|mimes:gif|max:18048',
'title' => ['required'],
'post_text' => ['required'],
'post_url' => ['required']
]);
//IMAGE JPG,PNG,SVG
if ($image = $request->file('post_image')) {
$destinationPath = 'media/uploads';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['post_image'] = "$profileImage";
}
//END IMAGE JPG,PNG,SVG
//VIDEO MP4
if ($image = $request->file('post_video')) {
$destinationPath = 'media/uploads';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$inputmp4 ['post_video'] = "$profileImage";
}
//END VIDEOS
// GIF IMAGES
if ($image = $request->file('post_gif')) {
$destinationPath = 'media/uploads';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$inputgif ['post_gif'] = "$profileImage";
}
//END GIF IMAGES
$post = $community->posts()->create
(['user_id' => auth()->id(),
'title' => $creds['title'],
'post_text' => $creds['post_text'],
'post_url' => $creds['post_url'],
'post_image' => $input['post_image'] ?? '',
'post_video' => $inputmp4['post_video'] ?? '',
'post_gif' => $inputgif['post_gif'] ?? '',
]);
return redirect()->route('communities.show', $community);
}
Is it possible post_video and post_gif are empty? Php has a max_upload and max post size limit that is defined on the ini file. It is possible that that size is being exceeded. Hence your files are not actually uploading.
Also, your if statements are kinda confusing. Check this out :
//This if statement will always return true. Since you're assigning $image variable to $request->file('post_video').
if ($image = $request->file('post_video')) {
//Code For saving file
//Don't use this
}
// Instead you should use hasFile to check if the file is uploaded. here's how
if ($request->hasFile('post_video')) {
$video = $request->file('post_video');
//Code For saving file
//Use This instead
}
Also, at the last line, where you call create() method, do this:
$post = $community->posts()->create
(['user_id' => auth()->id(),
'title' => $creds['title'],
'post_text' => $creds['post_text'],
'post_url' => $creds['post_url'],
'post_image' => $input['post_image'], // skip the "?? ''" part
'post_video' => $inputmp4['post_video'],
'post_gif' => $inputgif['post_gif'],
]);
Now, if either post_image, post_video or post_gif is empty, you'll get a error and can see if the data is wrong.
Also, on a kinda related note, did you know laravel has a good helper to save files in storage? Check it out

How can I store an image to the database from modal?

I want to store an Image through a modal, usually, I store images this way. But it never stores, it stores null on the database, like the file wasn't even uploaded. Everything else on the modal stores perfectly, except the image.
This is the code for the image on my controller.
if($request->hasFile('image')){
$file = $request->file('image');
$extension = $file->getClientOriginalExtension();
$filename = time() .'.'.$extension;
$file->move('uploads/event/',$filename);
$event->image = $filename;
}
In my view, this is how I upload the image.
<div class="text-center">
<img src='http://ssl.gstatic.com/accounts/ui/avatar_2x.png' width="300px" height="300px" class="avatar img-circle img-thumbnail" alt="avatar" name="image" >
</div><hr>
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" name="image" >
<label class="custom-file-label">Upload picture</label>
</div>
</div>
For the code I had, the only problem was that I didn't use the enctype="multipart/form-data". After looking for options, I found this and wrote it on the form of action and form-group div. It worked, the image stores and it also updates.
<form action="{{action('CalendarController#store')}}" method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<div class="modal-body">
<div class="form-group" enctype="multipart/form-data">
Since I got this working I will start implementing other codes for better performance and start to learn about the Storage in laravel. Thanks to all of you!
Try this on your Controller:
use Image;
public function store(CreateRequest $request)
{
$file = $request->file('image');
$imagename = $file->getClientOriginalName();
$imageext = $file->getClientOriginalExtension();
$path = 'upload/image/'.time().'.'.$imageext;
$image = Image::make($file);
$image->save($path);
$input = $request->all();
$input['image'] = $path;
$user = $this->userRepository->create($input);
return redirect(route('users.index'));
}
do the same with update() function
The file will store in /public/upload/image folder
You can also try and use the 'Intervention\Image' and File class:
composer require intervention/image
<?php
...
use File;
use Intervention\Image\Facades\Image
...
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = 'image.'.$image->getClientOriginalExtension();
$save_path = storage_path().'uploads/event/';
$path = $save_path.$filename;
$public_path = 'uploads/event/'.$filename;
// Make the user a folder and set permissions
File::makeDirectory($save_path, $mode = 0755, true, true);
// Save the file to the server
Image::make($image)->resize(300, 300)->save($save_path.$filename);
// Save the public image path
$event->image = $public_path;
$event->save();
}
return response()->json(['path' => $path], 200);
} else {
return response()->json(false, 200);
}

Insert data excel into 2 tables with id codeigniter

I have a problem with how to upload files excel with phpsreadsheet to the database. I want to put the data into two tables namely:
Beasiswa contain table: beasiswa_nama, beasiswa_id, beasiswa_file (link file), beasiswa_tahun, DATE_CREATED, DATE_UPDATED.
data_mahasiswa table cotain table: id_mhs, nama_mhs, nim_mhs, (FK) id_beasiswa
How to insert a file and read it to the Beasiswa table, and student data to data_mahasiswa?
Relation table:
Error create data:
Beasiswa Controller
public function create()
{
$this->form_validation->set_rules('nama_beasiswa', 'Nama Beasiswa', 'trim|required');
$this->form_validation->set_rules('tahun_beasiswa', 'Tahun Mahasiswa', 'trim|required');
if (empty($_FILES['nama_mahasiswa_beasiswa']['name'])) {
$this->form_validation->set_rules('nama_mahasiswa_beasiswa', 'File Nama Mahasiswa', 'required');
}
if ($this->form_validation->run() == TRUE) {
// true case
$upload_nama_mahasiswa = $this->_upload_nama_mahasiswa();
$data = array(
'beasiswa_nama' => htmlspecialchars($this->input->post('nama_beasiswa', true)),
'beasiswa_tahun' => htmlspecialchars($this->input->post('tahun_beasiswa', true)),
'beasiswa_file' => $upload_nama_mahasiswa,
'date_created' => date("Y-m-d H:i:s")
);
$create = $this->m_beasiswa->create($data);
if ($create == true) {
$this->session->set_flashdata('success', 'Berhasil Upload Data Beasiswa');
redirect('beasiswa/', 'refresh');
} else {
$this->session->set_flashdata('errors', 'Terjadi Galat. Silahkan Periksa Kembali!!');
redirect('beasiswa/create', 'refresh');
}
} else {
$this->render_template('beasiswa/create', $this->data);
}
}
private function _upload_nama_mahasiswa()
{
$filename = 'import-data';
$config['upload_path'] = 'assets/file/beasiswa/';
$config['file_name'] = $filename;
$config['overwrite'] = TRUE;
$config['allowed_types'] = 'xlsx|xls';
$config['max_size'] = '1024';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('nama_mahasiswa_beasiswa')) {
// $error = array('errors' => $this->upload->display_errors('File yang anda masukkan tidak sesuai permintaan, atau file terlalu besar.'));
$this->session->set_flashdata('errors', 'File yang anda masukkan tidak sesuai permintaan, atau file terlalu besar.');
redirect('beasiswa/create', 'refresh');
} else {
$data = array('upload_data' => $this->upload->data());
$img = $data['upload_data']['file_name'];
$excelReader = new PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$loadExcel = $excelReader->load($config['upload_path'] . $img);
$sheet = $loadExcel->getActiveSheet()->toArray(null, true, true, true);
$dataExcel = array();
// $this->data['sheet'] = $sheet;
$numRow = 3;
foreach ($sheet as $row) {
if ($numRow > 3) {
array_push(
$dataExcel,
[
'nama_mhs' => $row['A'],
'nim_mhs' => $row['B']
]
);
}
$numRow++;
}
$this->db->insert_batch('data_beasiswa', $dataExcel);
unlink($config['upload_path'] . $img);
}
}
Beasiswa Model
public function create($data)
{
if ($data) {
$insert = $this->db->insert('beasiswa', $data);
return ($insert == true) ? true : false;
}
}
Beasiswa View
<?php
defined('BASEPATH') or exit('No direct script access allowed');
?>
<!-- Main Content -->
<div class="main-content">
<section class="section">
<div class="section-header">
<div class="section-header-back">
<i class="fas fa-arrow-left"></i>
</div>
<h1>Tambah Beasiswa</h1>
</div>
<div class="section-body">
<div class="row">
<div class="col-md-12 col-xs-12 col-xl-12 col-12">
<div id="messages"></div>
<?php if ($this->session->flashdata('success')) : ?>
<div class="alert alert-success alert-dismissible">
<div class="alert-body">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<?php echo $this->session->flashdata('success'); ?>
</div>
</div>
<?php elseif ($this->session->flashdata('errors')) : ?>
<div class="alert alert-danger alert-dismissible show fade">
<div class="alert-body">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<?php echo $this->session->flashdata('errors'); ?>
</div>
</div>
<?php endif; ?>
<div class="card">
<div class="card-body">
<b style="font-size: 17px">Unduh format excel data mahasiswa</b><br>
Download template
<form action="<?php base_url('beasiswa/create') ?>" method="POST" enctype="multipart/form-data">
<div class="form-group">
<div class="section-title">Nama Program Beasiswa</div>
<input type="text" class="form-control" name="nama_beasiswa" id="nama_beasiswa" placeholder="Nama Program Beasiswa" value="<?= set_value('nama_beasiswa'); ?>">
<?= form_error('nama_beasiswa', '<small class="text-danger">', '</small>'); ?>
</div>
<div class="form-group">
<div class="section-title">Tahun Beasiswa</div>
<input type="text" class="form-control" name="tahun_beasiswa" id="tahun_beasiswa" placeholder="Tahun Beasiswa (contoh: 2020)" value="<?= set_value('tahun_beasiswa'); ?>">
<?= form_error('tahun_beasiswa', '<small class="text-danger">', '</small>'); ?>
</div>
<div class="form-group">
<div class="section-title">Upload File Nama Mahasiswa</div>
<input type="file" name="nama_mahasiswa_beasiswa" id="nama_mahasiswa_beasiswa" class="form-control col-sm-6 col-md-6">
<p class="text-danger" style="font-style:italic"><b>* Upload file sesuai dengan format yang sudah disesuaikan</b></p>
</div>
<button type="submit" class="btn btn-primary">Simpan</button>
Kembali
</form>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
It is because foreign key error probably happening because you insert a null data in data_mahasiswa table.
There was empty space in your excel (that probably have been edited?) that are used in foreach ($sheet as $row). You can fix this with:
foreach ($sheet as $row) {
if ($numRow > 3) {
if($row['A'] != null && $row['B'] != null)
{
$dataExcel[] = array(
'nama_mhs' => $row['A'],
'nim_mhs' => $row['B']
);
}
/*you can also break the function, if no empty row between data in your excel*/
/*else
{
break;
}*/
}
}
you need to get rid of the null value when you input the data to the database. above this line of your code at Beasiswa Controller
$this->db->insert_batch('data_beasiswa', $dataExcel);
add this line of code to delete cell that have null data
foreach ($dataExcel as $data => $val) {
if(empty($val['nama_mhs'])){
unset($dataExcel[$data]['nama_mhs']);
unset($dataExcel[$data]['nim_mhs']);
}
}
$dataExcel = array_filter($dataExcel);
$data = array('data_excel' => $dataExcel);

Storing Pictures To mysql Using Laravel

I'm trying to store some upload pictures to my database using laravel. Everything goes well, everything got stored, but for the file, they keep storing a bin file of 38B, I've tried reading it to .Txt files and it has a path to /Applications/MAMP/tmp/php/phpUzMXbn.
Here is my function code :
Route::post('/FruitCreate',function(Request $request){
$fruit = new fruit;
$fruit->name = $request->name;
$fruit->price = $request->price;
$fruit->picture = $request->image;
$fruit->save();
return redirect('FruitsChangingPricePanel');
My form blade :
<form enctype="multipart/form-data" method="POST" action="{{ url('FruitCreate') }}" >
{{ csrf_field() }}
<input type="text" name='name'>
<input type="text" name='price'>
<input type="hidden" name="MAX_FILE_SIZE" value="30000000" />
<input type="file" name='image'>
<button type='submit'> submit </button>
thank u For Your Help !!
You can do may be something like that:
$file = $request->file('image');
$imageContent = $file->openFile()->fread($file->getSize());
$fruit = new fruit; $fruit>picture = $imageContent; $fruit>save();
Note: Your column type must be Blob
because you are trying to save directly bin.
try this one
$file = Input::file('file');
$destinationPath = public_path(). '/uploads/';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
echo $filename;
//echo '<img src="uploads/'. $filename . '"/>';
$user = ImageTest::create([
'filename' => $filename,
]);
Firstly, you should get your image and then store it to public/uploads/fruits folder.And after that, you are saving the path to your picture to DB.
$fruit = new fruit;
$fruit->name = $request->name;
$fruit->price = $request->price;
if ($request->has('image')) {
if (!file_exists(public_path('uploads/fruits/'))) {
mkdir(public_path('uploads/fruits/'));
}
if (!file_exists(public_path('uploads/fruits/' . date('FY') . '/'))) {
mkdir(public_path('uploads/fruits/' . date('FY') . '/'));
}
$image = $request->file('image');
$filename = public_path('uploads').'/fruits/' . date('FY') . '/' . str_random() . '.' . $image->guessExtension();
\Image::make($image->getRealPath())->encode('jpg')->resize(220, 220)->put($filename);
$fruit->picture = $filename;
}
$fruit->save();

How to click button using Mechanize in perl?

<input type="hidden" name="hiddenConsolidateFiles" value="0">
<button type="button" style="width:220px;" onClick="javascript:viewFullTextOfTreaty()" value="full" name="full" id="full">View Full Text of Treaty</button>
<button type="button" style="display:none;" onClick="javascript:viewFullText()" value="" id="sim">View Other Relevant Treaty Information</button>
<button type="button" style="display:none;" onClick="javascript:viewConsolidated()" value="consol" name="consol" id="consol">View Consolidated Version of Treaty</button>
I have the above HTML. I want to click the button named full using Mechanize in perl. How can I do this?
I have tried $mech->click("full") and $mech->click_button(name => 'full') and $mech->click_button(value => 'full') but none have worked. They all say there is "no clickable input with name full".
I have no problems downloading your PDF:
my $url =
"http://ec.europa.eu/world/agreements/downloadFile.do?fullText=yes&treatyTransId=520";
{
my $mech = WWW::Mechanize->new();
$mech->get($url);
my ($filename) = $mech->{res}->{_headers}->{"content-disposition"} =~ m{filename=([^"]+)};
$mech->save_content($filename);
};
UPDATE
my $url =
"http://daccess-ods.un.org/access.nsf/Get?Open&DS=A/HRC/WGAD/2015/28&Lang=E";
my $mech = WWW::Mechanize->new();
$mech->get($url);
$mech->save_content("1.htm");
#HTTP-EQUIV="refresh" URL
my ($tmp_url) = $mech->content() =~ m{URL=([^"]+)};
$mech->get( "http://daccess-ods.un.org" . $tmp_url );
$mech->save_content("2.htm");
my ($pdf_url) = $mech->content() =~ m{URL=([^"]+)};
my ($cookie_url) = $mech->content() =~ m{src\s*=\s*"([^"]+)};
#First we need to get cookies
$mech->get($cookie_url);
#Next we can load PDF file
$mech->get($pdf_url);
$mech->save_content("Result.pdf");
Important note:
Parsing HTML with regular expressions is really bad idea (my favorite module is HTML::TreeBuilder::LibXML)