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
Related
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
I am trying to do a file check in an MVC framework, and even if I put the file with a jpg format, I am getting error
This is the function that checks the format
public function addAction()
{
$upload = new Upload();
if($this->request->isPost())
{
$allowed = array('gif','png' ,'jpg');
$filename = $_FILES['file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed))
{
echo 'error';
}
$this->request->csrfCheck();
$upload->assign($this->request->get());
$upload->user_id = Users::currentUser()->id;
if($upload->save())
{
Router::redirect('upload');
}
}
$this->view->uploas = $upload ;
$this->view->displayErrors = $upload->getErrorMessages();
$this->view->postAction = PROOT . 'upload' . DS . 'add';
$this->view->render('upload/add');
}
And this is the HTML code:
<div class="col-lg-6 upload-position center" >
<input type="file" id="file" name="file" >
</div>
The isPost method checks if the form method is post
For the next one looking for it :)
To upload a file you will need enctype="multipart/form-data":
<form enctype="multipart/form-data">
<input type="file" name="file"/>
</form>
Currently, I have 2 upload forms and 2 functions, uploadImage(); and uploadAlbum();. I have been wondering if I could remove the single image form and use the multi image form for both cases. If only 1 image is selected in the multi image form, a single image would be uploaded and if more than 1 images are uploaded, an album would be uploaded.
That would make the upload view look better since it won't have 2 identical upload forms and it would only require 1 function on the back-end that would determine whether it's a single image or an album based on the amount of images uploaded.
I don't really see any downsides to it but I wanted to make sure before reworking the code.
My upload view:
<form class='uploadForm' action="{{ route('imageUpload') }}" method="POST" enctype="multipart/form-data">
<label for="name">Image Name</label>
<input class='input' type="text" name="name" placeholder="Image Name">
<label for="description">Image Description</label>
<input class='input' type="text" name="description" placeholder="Description">
<input type="file" name="image"> {{ csrf_field() }}
<button class='Submit' type="submit" name="submit">UPLOAD</button>
</form>
<form class='uploadForm' action="{{ route('albumUpload') }}" method="POST" enctype="multipart/form-data">
<label for="albumName">Album Name</label>
<input class='input' type="text" name="albumName" placeholder="Album Name">
<label for="albumDescription">Image Description</label>
<input class='input' type="text" name="albumDescription" placeholder="Description">
<input type="file" name='files[]' multiple> {{ csrf_field() }}
<button class='Submit' type="submit" name="submit">UPLOAD</button>
</form>
My uploadImage() and uploadeAlbum() functions:
public function uploadAlbum(Request $request){
$name = $request['albumName'];
$description = $request['albumDescription'];
$tag = $request['tags'];
$userId = auth()->user()->id;
$files = $request->file('files');
$path = 'storage/uploads/albums/'.$name;
$fileOriginalName = $files[0]->getClientOriginalName();
$fileName = pathinfo($fileOriginalName, PATHINFO_FILENAME);
$extension = $files[0]->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
$fileNameToStore = str_replace(' ', '', $fileNameToStore);
$album = new Album();
$album->name = $name;
$album->description = $description;
$album->user_id = $userId;
$album->thumbnail = $fileNameToStore;
$album->save();
$album->tags()->attach($tag);
if(!File::exists($path)) {
File::makeDirectory(public_path($path));
}
if (is_array($files) || is_object($files)){
foreach ($files as $file){
$fileOriginalName = $file->getClientOriginalName();
$fileName = pathinfo($fileOriginalName, PATHINFO_FILENAME);
$extension = $file->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
$fileNameToStore = str_replace(' ', '', $fileNameToStore);
$file->storeAs('public/uploads/albums/'.$name, $fileNameToStore);
$file->storeAs('public/uploads/albums/'.$name.'/thumbnails/', $fileNameToStore);
$thumbnailImage = InterventionImage::make('storage/uploads/albums/'.$name.'/thumbnails/'.$fileNameToStore)->fit(400, 400, function ($constraint) {
$constraint->upsize();
});
$thumbnailImage->save();
$albumImage = new AlbumImage();
$albumImage->file_name = $fileNameToStore;
$albumImage->album_id = $album->id;
$albumImage->save();
}
}
return redirect()->route('albums');
}
public function uploadImage(Request $request){
$this->validate($request, [
'name' => 'required|max:120',
'description' => 'max:120|nullable',
'image' => 'required'
]);
$name = $request['name'];
$description = $request['description'];
$tag = $request['tags'];
$userId = auth()->user()->id;
$file = $request->file('image')->getClientOriginalName();
$fileName = pathinfo($file, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
$fileNameToStore = str_replace(' ', '', $fileNameToStore);
$request->file('image')->storeAs('public/uploads/images/',$fileNameToStore);
$request->file('image')->storeAs('public/uploads/images/thumbnails/',$fileNameToStore);
$request->file('image')->storeAs('public/uploads/images/specificImages/',$fileNameToStore);
$request->file('image')->storeAs('public/uploads/images/miniImages/',$fileNameToStore);
$thumbnail = InterventionImage::make('storage/uploads/images/thumbnails/'.$fileNameToStore )->resize(500, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$thumbnail->save();
$specificImage = InterventionImage::make('storage/uploads/images/specificImages/'.$fileNameToStore )->resize(2000, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$specificImage->save();
$miniImage = InterventionImage::make('storage/uploads/images/miniImages/'.$fileNameToStore )->fit(200, 200, function ($constraint) {
$constraint->upsize();
});
$miniImage->save();
$image = new Image();
$image->name = $name;
$image->description = $description;
$image->user_id = $userId;
$image->file_name = $fileNameToStore;
$image->save();
$image->tags()->attach($tag);
return redirect()->route('home');
}
This is possible of course. You would have to use the field that allows multiple
<input type="file" name="files[]" multiple />
When submitting the form you can check for if the $_POST['files'] array contains only one file. If it does, you can use the logic of a single file (image) and if it contains more you can use the logic of multiple files (album).
When you have this working you can also merge the majority of your logic and split it into multiple functions. One would be called with a foreach.
I want to upload a file using HTML input type file, but it doesn't working. The file doesn't uploaded to the expected folder and database (i want to store the file name to the table). It gives me no error appear when I inspect from browser. When I click the "Upload" button, the url is like http://localhost/mywebsite/ajax/upload? , method GET, Status Code 200 OK. What did I do wrong?
I am using mac, xampp, phpmyadmin, chrome.
Here's my view :
<form action="<?php echo site_url('admin/upload')?>" enctype="multipart/form-data">
<input type="file">
<button type="submit" class="btn btn-success"><span class="glyphicon glyphicon-upload" aria-hidden="true" ></span> Upload
</button>
</form>
The controller :
function upload()
{
if (!empty($_FILES))
{
$filename = $_FILES["file"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.'));
$file_ext = substr($filename, strripos($filename, '.'));
$tempFile = $_FILES['file']['tmp_name'];
$data = "admin".uniqid().$file_ext;
$targetPath = getcwd() . '/kirim_undangan/';
$targetFile = $targetPath . $data ;
move_uploaded_file($tempFile, $targetFile);
$data_user = array(
'request_id' => $request_id,
'status' => '1',
'filename_admin' => $uploadedFileName,
);
$this->load->model('excel');
$this->excel->upload_excel($data_user);
}
}
The model :
function upload_excel($allDataInSheet,$request_id)
{
$regex = "~\d{5}~";
array_shift($allDataInSheet);
foreach ($allDataInSheet as $key)
{
preg_match($regex, $key['B'], $result);
$data = array(
'request_id' => $request_id,
'to_name' => $key['A'],
'to_phone' => $key['C'],
'to_address' => $key['B'],
'to_zipcode' => $result[0],
'tariff' => '0'
);
$this->db->insert('excel', $data);
$this->db->update('request',$request_id);
}
}
You have to add a name to the input
<form method="post" action="<?php echo site_url('admin/upload')?>" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit" class="btn btn-success"><span class="glyphicon glyphicon-upload" aria-hidden="true" ></span> Upload
</button>
</form>
I want to upload files in to webroot/files folder, but my controller doing nothing, is there any mistake ?
View file name: uploadfile.ctp
Controller name: UploadFileController.php
Model name: UploadFile.php
In my view file I have:
<div class="files">
<input type="file" name="files[]" /><br/>
</div>
<button type="button" class="plus">+</button> <br><br>
<form name="frm1" method="post" onsubmit="return greeting()">
<input type="submit" value="Submit">
</form>
<?php echo $this->Html->script('addFile');
addFile script :
$(document).ready(function() {
$(".plus").click(function() {
$(".files").append("<input type='file' name='files[]'/><br/>");
});
});
And my Controller, I think that a mistake is somewhere here :
public function uploadFile() {
$uploadedFile = $this->request->params['UploadFile']['files[]']['tmp_name'];
$dir = WWW_ROOT . 'files/';
if ( !is_dir( $dir ) ) {
mkdir($dir);
chmod( $dir , 777);
}
$fileName = 'file_' . date( 'Y_m_d_h_i_s', time() );
move_uploaded_file( $uploadedFile, $dir. $fileName);
}
I got one Notice to:
Notice (8): Undefined index: UploadFile [APP\Controller\UploadFileController.php, line 7]
Thank you for any clue !
Solution
View File (uploadfile.ctp) :
<?php
echo $this->Form->create('uploadFile', array( 'type' => 'file'));
?>
<div class="input_fields_wrap">
<label for="uploadFilefiles"></label>
<input type="file" name="data[]" id="uploadFilefiles">
</div>
<button type="button" class="add_field_button">+</button> <br><br>
<form name="frm1" method="post" onsubmit="return greeting()">
<input type="submit" value="Submit">
</form>
<?php
echo $this->Html->script('addFile');
Controller (UploadFileController.php) :
class UploadFileController extends AppController {
public function uploadFile() {
$filename = '';
if ($this->request->is('post')) { // checks for the post values
$uploadData = $this->data;
//print_r($this->data); die;
foreach($uploadData as $file){
if ( $file['size'] == 0 || $file['error'] !== 0) { // checks for the errors and size of the uploaded file
return false;
}
$filename = basename($file['name']); // gets the base name of the uploaded file
$uploadFolder = WWW_ROOT. 'files'; // path where the uploaded file has to be saved
$filename = $filename; // adding time stamp for the uploaded image for uniqueness
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder); // creates folder if not found
}
if (!move_uploaded_file($file['tmp_name'], $uploadPath)) {
return false;
}
echo "Filename: $filename<br>";
}
}
}
}
Script (addFile.js) :
$(document).ready(function() {
var max_fields = 2;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x <= max_fields){
x++;
$(wrapper).append("<div><input type='file' name='data[]' id='uploadFilefiles'/><button href='#' class='remove_field'>Kustuta</button></div>");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on kustuta text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});