So this has been a problem for me for a while now and it just doesn't seem to work, I have a form where users can submit a new profile picure:
<form enctype="multipart/form-data" action="/profile" method="POST">
<input type="file" name="avatar">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="pull-right btn btn-sm btn-primary">
</form>
When the button is clicked they are being redirected to the controller which activates the following function:
public function update_avatar(Request $request)
{
$avatar = $request->avatar;
$extension = File::extension($avatar);
$filename = time() . '.' . $extension;
Image::make($avatar)->resize(350, 350)->save( public_path('/uploads/avatars/' . $filename ) );
$user = Sentinel::getUser();
$user->profile->avatar = $filename;
$user->save();
}
But whatever I do the controller always returns the message
(1/1) NotReadableException
Image source not readable
Does anyone know how I can fix this?
EDIT: I've changed my Image::make line to the following:
$image = Image::make($avatar->getRealPath())->resize(350, 350)->save( public_path('/uploads/avatars/' . $filename ) );
But now I am encountering a new error:
(1/1) FatalErrorException
Call to a member function getRealPath() on string
Try this instead :
Image::make($avatar->getRealPath())->resize(350, 350)->save( public_path('/uploads/avatars/' . $filename ) );
Edit:
use this, to retrieve your UploadedFile
$avatar = $request->file('avatar');
Edit #2:
For the extension use this instead :
$extension = $avatar->getClientOriginalExtension();
Note: Do not forget to authorize only images files in your validation rules.
Intead, you can "hardcode" the extension, Intervention is able to save & convert into the specified image format (jpg, png ..)
Related
I have stored my image with following code
if (isset($image)) {
// make unique name for image
$currentDate = Carbon::now()->toDateString();
$imagename = $slug . '-' . $currentDate . '-' . uniqid() . '.' . $image->getClientOriginalExtension();
// check category dir is exists
if (!Storage::disk('public')->exists('category')) {
Storage::disk('public')->makeDirectory('category');
}
// resize image for category and upload
$category = Image::make($image)->resize(1600,479)->stream();
Storage::disk('public')->put('category/'.$imagename,$category);
// check category slider dir is exists
if (!Storage::disk('public')->exists('category/slider')) {
Storage::disk('public')->makeDirectory('category/slider');
}
// resize image for category slider and upload
$slider = Image::make($image)->resize(500,333)->stream();
Storage::disk('public')->put('category/slider/'.$imagename,$slider);
} else {
$imagename = "default.png";
}
try with this code
<img src="images/icons8-team-355979.jpg" alt="Profile Image">
Failed to load resource: the server responded with a status of 404 (Not Found)
this is the error
Try this
<img src="{{url('category/slider')}}/{{ $category->image }}" alt="{{$category->name}}">
The url function will go to '/public' folder. So, you may need to edit your '/config/filesystem.php' so that the uploaded photo is saved inside the '/public' directory.
For more information on this please check this document.
When you want to serve files from the public disk directly, you need to create a symlink to these files. This is described in the documentation here: https://laravel.com/docs/5.7/filesystem#the-public-disk.
When you have done this, you can link to the assets using the asset() function.
echo asset('category/slider/icons8-team-355979.jpg');
I am using yii2. I am trying to select a file and then want to save it to my database table. I am using core PHP for it. Below is my code
<form action = <?=\yii\helpers\Url::toRoute(['meteracceptanceheader/import'])?> method ="post"
enctype="multipart/form-data">
.
.
.
.
.
.
.
<div class="row">
<div class="col-md-2">
Upload-Image
<input type="file" name="file"/>
<br />
<input type="submit" class="btn btn-primary pull-left" />
</div>
</div>
</form>
Controller
public function actionImport()
{
.
.
. // my other code
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileExt = explode('.',$fileName);
print_r($file);
die();
.
.
.
.
return $this->render('excel_finish', ['records_saved' => $ok_count,'status_arr'=>$status_arr]);
}
Database Table
In the above table, id is auto-increment accpt_id is the model id which I already have and file_path is the name of the file which should be saved like 123.jpg.
The file should be saved into a folder uploads/meter_acceptance/ and append with the file name.
Note:
I have already know how to upload images via the active form but here I want to do it in a traditional way.
Any help would be highly appreciated.
your controller should be like this
public function actionUpload(){
$model = new Images();
$uploadPath = Yii::getAlias('#root') .'/uploads/';
if (isset($_FILES['image'])) {
$file = \yii\web\UploadedFile::getInstanceByName('image');
$original_name = $file->baseName;
$newFileName = \Yii::$app->security
->generateRandomString().'.'.$file->extension;
// you can write save code here before uploading.
if ($file->saveAs($uploadPath . '/' . $newFileName)) {
$model->image = $newFileName;
$model->original_name = $original_name;
if($model->save(false)){
echo \yii\helpers\Json::encode($file);
}
else{
echo \yii\helpers\Json::encode($model->getErrors());
}
}
}
else {
return $this->render('upload', [
'model' => $model,
]);
}
return false;
}
i am trying to upload a photo using Image Intervention Package
i tried dd($request->hasFile('avator') ) and it return false
i returned "error" in my if statment just to make sure that i have an error
thanks in advance
public function update_photo(Request $request){
if($request->hasFile('avator') ){
$avator = $request->file('avator');
$filename = time() . '.' . $pic->getClientOriginalExtension();
Image::make($avator)->resize(300 , 300)->save(public_path('/uploads/avators' . $filename));
$user = Auth::user();
$user->avator = $filename ;
$user->save();
echo "hello world !";
}else {
echo " Error"; // just to make sure that i have an error
}
return view("profile" , array("user" => Auth::user() ));
}
first edit this line of code
$filename = time() . '.' . $avator->getClientOriginalExtension();
add to this slash also
Image::make($avator)->resize(300 , 300)->save(public_path('/uploads/avators/' . $filename));
*in your blade template make sure of spelling you are writing avator not avatar *
<input type="file" name="avator"/>
In your blade put this in your form tag:
enctype="multipart/form-data
and in your controller:
use File;
I have a form from which I gather quite a bit of information and am then required to upload Multiple Files.
All other aspects of the form are now working perfectly thanks to Devi on this forum. And to try and focus on only the one problem I now have I have decided to start the new thread: The previous / old thread can be viewed Insert into one Table, while updating another & File Upload
My problem now is to actually get the files to upload. My form is working in two parts. Part one is the basic HTML layout which then has the method pointing to the PHP file which handles the writing of info to the database tables.
The form has the following code for each file upload (There are 4 uploads, each for a different file reference, ie. License Document, Renewal Document, Identity Document, Other Documents):
<div class="form-group">
<label>Permit Renewal :</label>
<div class="input-group">
<label>
<input type="radio" class="minimal" value="0" <?php echo ($permit_renewal=='No')?'checked':'' ?> name="permit_renewal">
No
</label>
<label>
<input type="radio" class="minimal" value="1" <?php echo ($permit_renewal=='Yes')?'checked':'' ?> name="permit_renewal">
Yes
</label>
</div>
</div>
<div class="box-body">
<div class="form-group">
<div class="form-group">
<label for="scanned_permit_renewal">Attach File</label>
<input type="file" id="scanned_permit_renewal" name="scanned_permit_renewal">
<p class="help-block">Select a file to link to this outlet, the file name must be prefixed with the Outlet. E.g. 102987 - License 2016</p>
</div>
</div><!-- /.form-group -->
And the relevant processing part is
if (isset($_FILES["file"]["name"])) {
foreach($_FILES['file']['tmp_name'] as $key => $tmp_name){
$file_name = $key.$_FILES['file']['name'][$key];
$file_size =$_FILES['file']['size'][$key];
$file_tmp =$_FILES['file']['tmp_name'][$key];
$file_type=$_FILES['file']['type'][$key];
$new_file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . date("Ymd_his") . "_" . $file_name;
//echo $new_file;
move_uploaded_file($file_tmp,$new_file);
}
}
if($res1){
echo "Records added / updated successfully.";
}
header("refresh:2;url=../outlet_capture.php");
// close connection
$link->close();
I have also confirmed my rot directory and ensured that there is an /uploads/ folder present.
If don't see the definition, but it MUST have the enctype like
The $_FILES variable works with the name of the field in the form.
On your example it should be scanned_permit_renewal. And for access it from the PHP when the form was sent you should use $_FILES['scanned_permit_renewal'].
You uses on the foreach
foreach($_FILES['file']['tmp_name'] as $key => $tmp_name)
Which seems to be the problem.
IMHO you should use this:
foreach($_FILES as $fieldNameInTheForm => $file)
{
$file_name = $fieldNameInTheForm .$file['name'];
$file_size =$file['size'];
$file_tmp =$file['tmp_name'];
$file_type=$file['type'];
$new_file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . date("Ymd_his") . "_" . $file_name;
//echo $new_file;
move_uploaded_file($file_tmp,$new_file);
}
You have done everything right, you are simply not pointing to the right input names...
$_FILES['file'] does not exist. You should use $_FILES['scanned_permit_renewal'] instead just like when you access $_POST, the key is the name of the form field.
Actually, you are looping through the $_FILES['file'] as if you had put many inputs with the name file[*something*]. If you question is complete, you should simply be using
if (isset($_FILES["scanned_permit_renewal"])) {
$file_name = $_FILES['scanned_permit_renewal']['name'];
$file_size =$_FILES['scanned_permit_renewal']['size'];
$file_tmp =$_FILES['scanned_permit_renewal']['tmp_name'];
$file_type=$_FILES['scanned_permit_renewal']['type'];
$new_file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . date("Ymd_his") . "_" . $file_name;
//echo $new_file;
move_uploaded_file($file_tmp,$new_file);
}
To answer your comment, an efficient way of doing it could be 2 ways. First, which will require no PHP changes, rename your input fields to file[scanned_permit_renewal] this will let you use the foreach as you seem to intend.
Another way could be to use an array of possible inputs:
$file_inputs = array('scanned_permit_renewal','my','other','documents');
foreach($file_inputs as $input_name){
if (isset($_FILES[$input_name])) {
$file_name = $input_name.$_FILES[$input_name]['name'];
$file_size =$_FILES[$input_name]['size'];
$file_tmp =$_FILES[$input_name]['tmp_name'];
$file_type=$_FILES[$input_name]['type'];
$new_file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . date("Ymd_his") . "_" . $file_name;
//echo $new_file;
move_uploaded_file($file_tmp,$new_file);
}
}
A third way could be to just loop through the $_FILES array. But I wouldn't do that, as there could be anything there. You'll prefer to filter on your wanted files.
For uploading multiple files, input field should be:
<input type="file" id="scanned_permit_renewal" name="scanned_permit_renewal[]" multiple="multiple">
processing part:
if (count($_FILES["scanned_permit_renewal"]["name"]) > 0) {
foreach($_FILES['scanned_permit_renewal']['tmp_name'] as $key => $tmp_name)
{
$file_name = $key.$_FILES['scanned_permit_renewal']['name'][$key];
$file_size =$_FILES['scanned_permit_renewal']['size'][$key];
$file_tmp =$_FILES['scanned_permit_renewal']['tmp_name'][$key];
$file_type=$_FILES['scanned_permit_renewal']['type'][$key];
$file_to_save = date("Ymd_his") . "_" . $file_name;
$new_file = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" .$file_to_save;
//echo $new_file;
if(move_uploaded_file($file_tmp,$new_file)){
// update database
$query = "UPDATE `table` SET `field_name` = '".$file_to_save."' WHERE ..... ";
}
}
}
Cont. - Add File Uploader to Joomla Admin Component
I could able to upload file and save it on disk. But its not saving file name on the database.
How can i do it ?
Here is the controller -
class InvoiceManagerControllerInvoiceManager extends JControllerForm
{
function save(){
$file = JRequest::getVar('jform', null, 'files', 'array');
$path = JPATH_BASE;
// Make the file name safe.
jimport('joomla.filesystem.file');
$file['name']['invoice'] = JFile::makeSafe($file['name']['invoice']);
// Move the uploaded file into a permanent location.
if (isset($file['name']['invoice'])) {
// Make sure that the full file path is safe.
$filepath = JPath::clean($path. DS ."components". DS ."com_invoicemanager". DS ."files". DS .strtolower($file['name']['invoice']));
// Move the uploaded file.
JFile::upload( $file['tmp_name']['invoice'], $filepath );
}
return parent::save();
}
}
Form field in XML -
<field name="invoice" type="file"/>
UPDATE:
worked after adding following lines taken from #Andras Gera code
$data = JRequest::getVar( 'jform', null, 'post', 'array' );
$data['invoice'] = strtolower( $file['name']['invoice'] );
JRequest::setVar('jform', $data );
I've ran into the same problem, maybe we can go forward together. Here is my codes:
/administrator/components/com_comp_name/models/forms/edit.xml
<?xml version="1.0" encoding="utf-8"?>
<form addrulepath="/administrator/components/com_gonewsletter/models/rules">
<fieldset name="details">
<field
name="id"
type="hidden"
/>
<field
name="title"
type="text"
label="COM_GONEWSLETTER_EDIT_TITLE_LABEL"
description="COM_GONEWSLETTER_EDIT_TITLE_DESC"
size="40"
class="inputbox"
required="true"
default=""
/>
<field
name="date"
type="calendar"
label="COM_GONEWSLETTER_EDIT_DATE_LABEL"
description="COM_GONEWSLETTER_EDIT_DATE_DESC"
size="40"
class="inputbox"
required="true"
default=""
format="%Y-%m-%d"
/>
<field
name="published"
type="list"
label="JSTATUS"
description="COM_GONEWSLETTER_EDIT_PUBLISHED_DESC"
class="inputbox"
size="1"
default="0">
<option
value="1">JPUBLISHED</option>
<option
value="0">JUNPUBLISHED</option>
</field>
<field
type="file"
name="pdf_file"
label="COM_GONEWSLETTER_EDIT_FILE_LABEL"
default=""
description="COM_GONEWSLETTER_EDIT_FILE_DESC"
size="40"
accept="application/pdf"
class="fileuploader"
/>
<field
name="file"
type="hidden"
/>
</fieldset>
</form>
and
/administrator/components/com_comp_name/controllers/edit.php
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla controllerform library
jimport('joomla.application.component.controllerform');
/**
* GoNewsletter Controller
*/
class GoNewsletterControllerEdit extends JControllerForm
{
function __construct($config = array()) {
$this->view_list = 'List';
parent::__construct($config);
}
function save(){
// ---------------------------- Uploading the file ---------------------
// Neccesary libraries and variables
jimport( 'joomla.filesystem.folder' );
jimport('joomla.filesystem.file');
$data = JRequest::getVar( 'jform', null, 'post', 'array' );
// Create the gonewsleter folder if not exists in images folder
if ( !JFolder::exists( JPATH_SITE . DS . "images" . DS . "gonewsletter" ) ) {
JFolder::create( JPATH_SITE . DS . "images" . DS . "gonewsletter" );
}
// Get the file data array from the request.
$file = JRequest::getVar( 'jform', null, 'files', 'array' );
// Make the file name safe.
$filename = JFile::makeSafe($file['name']['pdf_file']);
// Move the uploaded file into a permanent location.
if ( $filename != '' ) {
// Make sure that the full file path is safe.
$filepath = JPath::clean( JPATH_SITE . DS . 'images' . DS . 'gonewsletter' . DS . strtolower( $filename ) );
// Move the uploaded file.
JFile::upload( $file['tmp_name']['pdf_file'], $filepath );
// Change $data['file'] value before save into the database
$data['file'] = strtolower( $filename );
}
// ---------------------------- File Upload Ends ------------------------
JRequest::setVar('jform', $data );
return parent::save();
}
}
If you print out the $data before send it to parent::save($data) it contains the right fields you want to save, but it doesn't. I tried to use an input type=text instead of type=file and it saves correctly.
I tried another way like: input type=file and name=pdf_file, after then I added a hidden field name=file default="". And then I've set up this hidden field value to filename without success. Maybe I was doing something wrong. Keep continue to figure out something.
You can use php move_uploaded_file() function
//import joomlas filesystem functions, we will do all the filewriting with joomlas functions
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
//this is the name of the field in the html form, filedata is the default name for swfupload
$fieldName = 'Filedata';
//the name of the file in PHP's temp directory that we are going to move to our folder
$fileTemp = $_FILES[$fieldName]['tmp_name'];
//always use constants when making file paths, to avoid the possibilty of remote file inclusion
$uploadPath = JPATH_SITE.DS.'path'.DS.'path'.DS.$fileName;
if(!JFile::upload($fileTemp, $uploadPath))
{
echo JText::_( 'ERROR MOVING FILE' );
return;
}
else
{
//Updating the db with the $fileName.
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query->update($db->nameQuote(TABLE_PREFIX.'table_name'));
$query->set($column.' = '.$db->quote($fileName));
$query->where($db->nameQuote('id').'='.$db->quote($id));
$db->setQuery($query);
$db->query();
}
$column - db column name of the file
$fileName - file name
Query is ran if the file is successfully uploaded.
set filename in request variable as it's now a $_FILES variable
JRequest::setVar('jform[invoice]',$file['name']['invoice'] );
//full code
class InvoiceManagerControllerInvoiceManager extends JControllerForm
{
function save(){
$file = JRequest::getVar('jform', null, 'files', 'array');
$path = JPATH_BASE;
// Make the file name safe.
jimport('joomla.filesystem.file');
$file['name']['invoice'] = JFile::makeSafe($file['name']['invoice']);
// Move the uploaded file into a permanent location.
if (isset($file['name']['invoice'])) {
// Make sure that the full file path is safe.
$filepath = JPath::clean($path. DS ."components". DS ."com_invoicemanager". DS ."files". DS .strtolower($file['name']['invoice']));
// Move the uploaded file.
JFile::upload( $file['tmp_name']['invoice'], $filepath );
JRequest::setVar('jform[invoice]',$file['name']['invoice'] );
}
return parent::save();
}
}
On joomla 3.2.x, I have to override save function of my model class to save the uploaded file name to db, like this
public function save($data){
$input = JFactory::getApplication()->input;
$files = $input->files->get('jform');
$fieldName = 'thumbnail';
$data['thumbnail'] = $files[$fieldName]['name'];
return parent::save($data);
}