I need to save the image for an avatar.
Can anyone give me a simple code to save and retrieve image?
I need to:
Save image in folder
Save image name in DB
Finally retrieve on image tag; I have to do it by Query Builder
Form:
<form action="" method="post" role="form" multiple>
{{csrf_field()}}
<legend>Form Title</legend>
<div class="form-group">
<label for="">Your Image</label>
<input type="file" name="avatar">
</div>
<button type="submit" class="btn btn-primary">save</button>
back
</form>
<img name="youravatar" src="">
</div>
Route:
Route::get('pic','avatarController#picshow');
Route::post('pic','avatarController#pic');
Controller:
I have the avatarController, but it is empty because I don't know what to do.
Database:
Table name: avatar
Fields: name id, imgsrc, created_at, Updated_at
Other:
I found this code but I can't find out anything:
if ($request->hasFile('avatar')) {
$file = array('avatar' => Input::file('avatar'));
$destinationPath = '/'; // upload path
$extension = Input::file('avatar')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('avatar')->move($destinationPath, $fileName);
}
First, make sure you have the encrypt attribute in your form
<form action="#" method="post" enctype="multipart/form-data">
You can use something similar to this in your controller
public function save(Request $request)
{
$file = $request->file('file');
// rename your file
$name = $file->getClientOriginalName();
\Storage::disk('local')->put($name, \File::get($file));
return "file saved";
}
Yes, you should store the file route in your database as well.
Make sure you are using a consistent path for your images like
Finally you have to create a route to give public access to your image file, like so:
Route::get('images/{file}', function ($file) {
$public_path = public_path();
$url = $public_path . '/storage/' . $file;
// file exists ?
if (Storage::exists($archivo))
{
return response()->file($pathToFile);
}
//not found ?
abort(404);
});
Check the docs about Laravel Responses
I hope this gives you an Idea of what to do.
Upload Image in laravel 5.4
check if request has image
$request->hasFile('image')
OR
$request->file('image')->isValid()
Now Save Image
$request->inputname->store('folder-name') return image path 'folder name/created image name
$request->image->store('images')
Check if image exits
Storage::disk('local')->exists('image name');
Delete Image
Storage::delete('image');
This is my code
if ($request->hasFile('image') && $request->file('image')->isValid())
{
$path = $request->image->store('images');
if(!empty($path)){
$edit = Model::FindOrFail($id);
// Delete old image
$exists = Storage::disk('local')->exists($edit->image);
if($exists){
Storage::delete($edit->image);
}
$edit->image = $path;
$edit->save();
}
}
Reference
Related
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);
}
I want to upload a csv file to my database via a laravel form. I can only insert file if the file is stored into public folder. How can I correctly set path with fopen function?
When submitting form, my code uses only the csv that already exists in public folder and not the csv I try to upload. Except from the csv I also pass some other data to my controller. How can I alter code to receive form file and not public folder stored file?
1) Below is my form excerpt. At the bottom lines I try to upload the file.
<body>
<form method='post' enctype="multipart/form-data" action="/hard">
{{csrf_field()}}
<section>
<br>
<legend><i><b> Complete Data Below</b></i></legend>
<br>
</section>
<section>
Choose program:
<select name="sc" id="xaos">
<optgroup label="postgraduates">
#foreach($transport as $y)
<option value="{{$y->object_id}}">{{$y->object_name}}</option>
#endforeach
</optgroup>
</select>
</section>
<br>
<section>
ID number:
<input name='am' type='number' min="1000000" max="1999999" required="" oninvalid="this.setCustomValidity('1000000 < Value < 1999999')">
</section>
<br>
<section>
Select Language:
<select name="language" id="lang">
<option value="GR"> Greek</option>
<option value="EN"> English</option>
</select>
</section>
<br>
<section>
<label for="upload-file">select csv file</label>
<input type="file" name="upload-file">
</div>
<input type='submit' name='upload' value="Submit!">
</section>
</form>
<br>
<br>
</body>
2) And below is my controller code excerpt which handles file imported.
public function job(Request $p)
{
$a1 = $p -> get('sc');
$a2 = $p -> get('am');
$a3 = $p -> get('language');
$f_rownum = 0;
if (($handle = fopen ( 'MOCK_DATA.csv', 'r' )) !== FALSE)
{
while ( ($data = fgetcsv ( $handle, 1000, ';' )) !== FALSE )
{
$ac1=$data[0];
$ac2=iconv("Windows-1253", "UTF-8", $data[1]);
$ac3=iconv("Windows-1253", "UTF-8", $data[2]);
$ac4=iconv("Windows-1253", "UTF-8", $data[3]);
$ac5=$data[4];
...............
According to Laravel documentation you can store your csv file into the storage like this:
public function storeFile(Request $request)
{
$path = $request->file('upload-file')->store('{directoryName}');
return $path;
}
The above code store your file in storage and returns tha path which you can save it into your DB.
For retrieving the file, you can use this code if you want to force user to download the file:
return Storage::download('{pathWhichYouSavedInDB}');
or you can retrieve the content of the file by using this code:
$contents = Storage::get('{pathWhichYouSavedInDB}');
[I add the extra response which I wrote in the comments]
fopen requires a full-path url of the stored file to be able to open it. So you can get the file url and then pass it to the fopen function like this:
$url = Storage::url('file.jpg');
Or you can not to use fopen at all and just use the $contents which you already retrieved with
$contents = Storage::get('{pathWhichYouSavedInDB}');
As my question states I am trying to use XQuery and a simple HTML form to upload files to my MarkLogic local database. I already connected to a HTTP-server.
My code now looks like this:
Form:
<div id="content">
<form name="test" action="upload.xqy?uid={xdmp:random()}" method="post"
enctype="multipart/form-data">
<p><label>File to upload:
<input type="file" class="name" name="upload" size="50"/></label></p>
<p><input type="submit" value="Upload and Get Results"/></p>
</form>
</div>
upload.xqy:
let $filename := xdmp:get-request-field-filename("upload")
let $collection := "semansysdocs"
let $fileLocation := xdmp:get-request-path()
return
xdmp:document-load($fileLocation,
map:map() => map:with("uri", $filename)
=> map:with("permissions", xdmp:default-permissions())
=> map:with("collections", $collection)
)
The docs simply state to use xdmp:document-insert(), but I do not understand where.
Is there a way to specify where the file is coming from to get the $fileLocation, or do i need an other method to do this?
Thank you!
Your form is already sending both filename and file data. xdmp:get-request-field-filename('upload') returns the original file path as sent by the browser, and xdmp:get-request-field('upload') will get you the data. I think you are looking for something like:
let $filename := xdmp:get-request-field-filename("upload")
let $file := xdmp:get-request-field("upload")
let $collection := "semansysdocs"
return
xdmp:document-insert(
$filename,
$file,
xdmp:default-permissions(),
(xdmp:default-collections(), $collection)
)
HTH!
I have a problem with refreshing upload file form. First time when I clik Upload File it uploads file on server (folder uploads/), and path name uploads in mysql base (table 'files'). When I refresh that page it duplicates same path name in mysql base, it does not duplicate file in uploads/. I found similar solutions but not my case, where I need to stay on the same page, and list all uploaded files. Here is the form code :
<?php
if(isset($_POST['upload'])){
$targetfolder = "uploads/";
$target_file = $targetfolder . basename( $_FILES['file']['name']) ;
$ok=1;
$file_name = $_FILES['file']['name'];
$file_type=$_FILES['file']['type'];
if ($file_type=="application/pdf" || $file_type=="image/gif" || $file_type=="image/jpeg" || $file_type== "application/msword" || $file_type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ) {
if ($ok == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
$sql = "INSERT INTO files (path, profesor, struka) VALUES ('" .$file_name. "', '". $_SESSION['username']. "','')";
if (mysqli_query($link, $sql)){
}else {echo "ERROR connecting database $sql".mysqli_error($link);
}
} else {
echo "Sorry, there was an error uploading your file.";
}
}}
else {
echo "Sorry only PDF, DOCX, JPEG, GIF.<br>";
}}
?>
<div class = "upload">
<form method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Select file for upload:</br>
<input type="file" name="file" >
<input type="submit" id = "button_upload" value="Upload File" name="upload">
</form>
</div>
first, i don't see a place in your code, where you actually show the list of uploaded files.
second - if you refresh your page, the form is submited one more time, so another insert is done with the same data. you don't see the duplicate file, because it is just overwritten.
so, after you successfully inserted and uploaded, you should do a redirect to the same page, for example with header('Location: yourscript.php'). in this case POST will not be set.
I tried searching but no success i want to upload max 5 images to database along with user form data.I have table where all user data of form posted is saved along with images uploaded[image upload is attached with user form] picture fields in database are named as pic1,pic2,pic3.. pic5 + email,password etc I am successfull in uploading image data to database but not images.
//controller
if ($this->form_validation->run()!=true) {
$data['countryDrop'] = $this->Country_states_cities->getCountries();
$this->load->view('header');
$this->load->view('register',$data); //Display page
$this->load->view('footer');
}else{
$form=array();
$form['first_name']=$this->input->post("first_name",true);
$form['last_name']=$this->input->post("last_name",true);
$form['dob']=date('Y-m-d',strtotime($this->input->post("dob",true)));
$form['email']=$this->input->post("email",true);
$form['password']=sha1($this->input->post("password",true));
$form['phone']=$this->input->post("phone",true);
$form['addline2']=$this->input->post("addressline2",true);
$form['zip']=$this->input->post("zip",true);
$result = $this->Couch_reg->insert_new_user($form); //call to model
//model
function insert_new_user($form)
{
$this->db->insert('tbl_usrs',$form);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
}
//view
<input type="file" name="uploadfile[]" accept = "image/*" multiple = "multiple" size="20" /> <br />
as we can see model part is very short i want to collect images name in array form and send it to database.
You need to save the images in the upload folder and save the image name in the database.
<html>
<body>
<form method="POST" action="<?php echo site_url('my-controller/file_upload');?>" 'enctype'=>'multipart/form-data'>
<label for="file">Filename:</label>
<input type="file" name="userfile[]" id="file" multiple>
<input type="submit" value="upload"></form>
</body>
</html>
Then create controller
make funtion inside it:
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$fileName = $_FILES['userfile']['name'];
$images[] = $fileName;
Hope this will help you.
For more you can try this: http://w3code.in/2015/09/upload-file-using-codeigniter/