I am working a CI developer since from 1 year and i didn't face this type of error. I try to get image name through post but it will give me image like this: c:\fakelink\imagename, i don't know what's the issue kindly help me to solve this issue.
Here is my view code:
<form id="profile_update" enctype="multipart/form-data">
<div class="form-group">
<img src="<?php echo base_url()?>public/assets/plugins/images/users/varun.png" class="thumb-lg img-circle" alt="img">
<div class="row">
<div class="form-group col-sm-6">
<input type="file" class="form-control" id="user_image" name="user_image">
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
here is Ajax Code:
type: "POST",
url: base_url + "admin/update_profile",
data: 'user_image=' + user_image,
here is Model Code:
$config = array(
'upload_path' => './uploads/',
'allowed_types' => 'gif|jpg|png|jpeg',
'max_size' => '2048',
);
if($_FILES['user_image']['name'] != '') {
$image = 'user_image';
$upload_data = $this->do_upload($image, $config);
if ($upload_data['condition'] == 'error') {
echo json_encode(array('condition' => 'error', 'message' => $upload_data['error'] . ' (Profile image)'));
exit;
} else {
$account_array['foto'] = $upload_data['upload_data']['file_name'];
}
}
The error is located on this line:
if($_FILES['user_image']['name'] != '') {
Thanks to all for any help.
Your Ajax code is not correct. Add these lines to your Ajax:
var formdata = new FormData ($('#profile_update')[0]); //get form data using HTML5 FormData Object
$.ajax({
type: "POST",
url: base_url + "admin/update_profile",
data: formdata,
contentType: false, //set content type to false so that the browser will set the content type to multipart
processData: false, //Also set process data to false so that the data being sent will not be serialized
success: function(res){
//Success function goes here..
}
});
Use **name user_image instead of id.**
Related
So im building my own website and i have this feature wherein a logged-in user can upload and change his avatar. it is my first time doing this so i am having a hard time making this work. i'll provide the codes below, you guys might see the faults that i dont know. it will be greatly appreciated if you can provide links that will help me improve. thanks in advance!
Blade.php file
<form method='POST' action="{{ route('image-upload') }}" enctype="multipart/form-data">
#csrf
<div class=" overflow-auto" style="padding-top:5%">>
<div class="p-3">
<div class="card">
<div class="card-body" >
<h4 class="card-title text-info"><strong> Attach your picture </strong></h4>
<div class="row justify-content-center">
<div class="col-sm-12 col-lg-4">
<div class="form-group row">
<label for="step5_picture" class="col-sm-3 text-right control-label col-form-label">Please upload your photo here:</label>
<div class="col-sm-9">
<input class="form-control" type="file" value="" id='upload_picture' >
</div>
</div>
</div>
</div>
Next
<button class="btn btn-lg waves-effect waves-light btn-info" id="btn-upload" style="float:right; margin-right:10px;">Upload</button>
</div>
</div>
</div>
</div>
</form>
Ajax code
$("#btn-upload").click(function(e){
e.preventDefault();
var data = {
'photo_filename': $('#upload_picture').val(),
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "/image-upload",
data: data,
dataType: "json",
success: function (response) {
}
});
});
});
Controller.php file The name of the column in my database is also photo_filename
public function image-upload(Request $request,){
$data = UserInfoModel::where('app_id', '=' ,Session::get('loginId'))->first();
$validator=Validator::make($request->all(), [
'photo_filename' => 'required',
'photo_filename.*' => 'image|mimes:jpeg,png,jpg,svg|max:5000'
]);
if($request->hasfile('photo_filename')){
$data->update([
'photo_filename' => $request->input('photo_filename')
]);
$photo = $request->file('photo_filename')->getClientOrginalName();
$destination = public_path() . '/public/image';
$request->file('photo_filename')->move($destination, $photo);
return back()->with('success', 'Your image has been successfully uploaded!');
}
}
Web.php file
Route::post('/image-upload',[CustomAuthController::class, 'image-upload'])->name('image-upload');
I am getting a payload and here it is
No error but still not uploading
Here's a minimal working example to create file upload in Laravel:
blade file:
<form method="POST" enctype="multipart/form-data" action="{{ route('save') }}">
#csrf
<input type="file" name="image" placeholder="Choose image" id="image">
<button>Send</button>
</form>
Controller:
public function save(Request $request) {
$path = $request->file('image')->store('public/images');
return $path;
}
web.php:
Route::post('/foobar', [\App\Http\Controllers\FoobarController::class, 'save'])->name('save');
Please note Ajax call is not necessary here, since html form will do the POST call with the CSRF token.
Also please note that using hyphens in function names won't work in php.
use FormData to send file in form, and add contentType: false and processData: false, you can read function setting contentType and processData in here https://api.jquery.com/jquery.ajax/
var formData = new FormData();
formData.append('photo_filename', $('#upload_picture')[0].files[0])
$.ajax({
url: "/image-upload",
type: "post",
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function(response) {
}
});
Since a lot of days I am trying to upload file in the server I got 405 methods not allowed error in live server:
This is my view:
HTML & javascript
#extends('layouts.app')
#section('content')
form id="uploaddiamond" class="form-horizontal form-label-left" method="post" enctype="multipart/form-data">
#csrf
<div class="col-md-6">
<div class="block">
<div class="panel-body">
<div class="form-group">
<label class="col-md-3 control-label">Upload Diamond <span class="required">*</span></label>
<div class="col-md-9">
<input required="" type="file" name="result_file" id="result_file" />
</div>
</div>
<div class="btn-group pull-right">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
</div>
</div>
</form>
#endsection()
#section('javascript')
<script>
$("#uploaddiamond").on("submit",function(e) {
e.preventDefault();
console.log('tst');
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name=_token]').attr('content')
}
});
var file_data = $('#result_file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "{{ route('diamond') }}", // point to server-side PHP script
data: form_data,
type: 'POST',
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false,
success: function(data) {
console.log(data);
}
});
});
</script>
#endsection()
This is my web route:
Route::get('/imageview','ImageController#index')->name('getimage');
Route::post('/postDiamond','ImageController#postDiamond')->name('diamond');
This is my controller:
public function index(){
return view('Image/imgupload');
}
public function postDiamond(Request $request){
dd($request->file('file'));
$supplier_name = $request->supplier_name;
$extension = $request->file('file');
$extension = $request->file('file')->getClientOriginalExtension(); // getting excel extension
$dir = 'assets/files/';
$filename = uniqid().'_'.time().'_'.date('Ymd').'.'.$extension;
$request->file('file')->move($dir, $filename);
}
I don't why this code is not working cause this code works in localhost but, not working in Linux hosting:
Can someone help do I have did a mistake on version something
server current PHP version:7.3.17
laravel PHP version:7.1.10
This is my server error image please check:
enter image description here
enter image description here
Well I have just tested this code on live server and it's working fine. If this code still doesn't work for you then you need to check permissions on server side for some files like web.php etc...
$(document).on('click','#submit_button', function(e){ //#submit_button id on submit button
e.preventDefault();
var formData = new FormData(this.form);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
}
});
$.ajax({
method: 'POST',
url: '{{ route("diamond") }}',
cache: false,
contentType: false,
processData: false,
data: formData,
success: function(data){
console.log(data);
},
error: function(data){
console.log(data);
}
});
});
Be sure to remove #csrf from your <form> tag.
In controller just dd(request()->all()); and see what you get
I have a form in which I am taking file input that is image, then I send data to my controller with a ajax call but my controller is not getting any file. It is showing me the error {"error":"You did not select a file to upload.</p>"}
My Form
<form action="#" id="formParking" enctype="multipart-form-data">
<div class="input-group">
<div class="col-xs-12 col-sm-4 no_padding">
<label class="">Attachment</label>
</div>
<div class="col-xs-12 col-sm-8">
<div class="col-xs-12 no_space"><input type="file" id="images" name="images" multiple="multiple" /></div>
</div>
</div>
<div class="input-group">
<div class="col-xs-12 col-sm-4 no_padding"> </div>
<div class="col-xs-12 col-sm-8"> <a class="btn blue green text-center" id="btnSave" onclick="saveParking()" >Add</a> </div>
</div>
</form>
Ajax Call
function saveParking()
{
var url;
url = "link_to_controller_function";
$.ajax({
url : url,
type: "POST",
data: $('#formParking').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
location.reload();
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
My Controller
$config['upload_path'] = base_url().'uploads';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 11111;
$config['max_height'] = 76118;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('images'))
{
$error = array('error' => $this->upload->display_errors());
echo json_encode($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
echo json_encode($data);
}
Addd processData and contentType in your ajax to deal with form when you are posting it using ajax
$.ajax({
url : url,
type: "POST",
data: $('#formParking').serialize(),
dataType: "JSON",
processData: false,
contentType: false,
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
location.reload();
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
also add this attribute enctype="multipart/form-data" to your form tag as
<form action="#" id="formParking" enctype="multipart/form-data">
correct this
enctype="multipart/form-data"
it seems there is the problem with your ajax code, please use FormData instead of serialize for file upload.
Example:
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$("#gallery").html(data);
},
error: function(){}
});
}));
For more info See: http://phppot.com/jquery/php-ajax-multiple-image-upload-using-jquery/
the ajax submission
$("#ID").submit(function(e){
e.preventDefault();
var formData = new FormData(this);
jQuery.ajax({
url : $(this).attr('action') or url,
type : $(this).attr('method') or method,
data : formData,
success:function(response){
//do whatever you want
},
cache: false,
contentType: false,
processData: false
});
});
Your Have to change
$config['upload_path'] = base_url().'uploads';
to
$config['upload_path'] = './uploads/';
on base_url().'uploads' you are pointing the path to a website.
and of course you have to create uploads directory In root.
Hello I'm using Codeigniter 3 and jQuery ajax.
I'm using the built in upload library...
I want to upload image on my server, but always get this error message:
You did not select a file to upload.
Here is my code
View
<?php echo form_open_multipart('settings/uploadprofilephoto', array('id' => 'upload-avatar-form'));?>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Upload profile photo</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<div class="row">
<div class="form-group col-md-6">
<input type="file" name="profilephoto" id="profile-photo" class="form-control">
</div>
<div class="form-group col-md-6">
<button type="submit" id="upload" class="btn btn-success">Upload</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<?php echo form_close();?>
Controller
public function uploadProfilePhoto(){
$config = array(
'upload_path' => base_url() . 'uploads/test',
'allowed_types' => 'jpg|jpeg|gif|png',
'min_height' => 480,
'min_width' => 640,
'remove_spaces' => true,
);
$this->load->library('upload', $config);
if($this->upload->do_upload("profilephoto")){
$data = array(
'status' => true,
'messages' => 'Uploaded'
);
echo json_decode($data);
}else{
$data = array(
'status' => false,
'messages' => $this->upload->display_errors()
);
echo json_encode($data);
}
}
ajax
/*
Upload profile photo
*/
$("#upload-avatar-form").submit(function(event){
$.post(base_url + "settings/uploadprofilephoto" , $(this).serialize(), function(data){
console.log(data);
//alert("ok");
});
event.preventDefault();
});
Where am I wrong?
serialize() will not pass image within it. It does not work with multipart formdata.
Instead use like this:
var formData = new FormData(this);
Pass this formData variable instead of $(this).serialize()
Try this
$('#button_name').on('click', function(event) {
event.preventDefault();
$.ajax({
url: "<?php echo base_url('settings/uploadprofilephoto');?>",
type: 'post',
dataType: 'json',
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function(json) {
// Success Stuff
},
});
});
On the view part
<button type="button" id="button_name">Upload</button>
You have to try this
$('#logo_form').on('submit',function(form){
form.preventDefault();
var me = $(this);
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: me.attr('action'), // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$("#logo_form")[0].reset();
$('#logo_success').html(response); // display success response from the server
window.setTimeout(function(){location.reload()},1000);
},
error: function (response) {
$('#error').html(response); // display error response from the server
}
});
});
Please check below mentioned solution, This will help you to send file with input data.
var myFormData = new FormData();
$(document).on("click", "button", function(e) {
e.preventDefault();
var inputs = $('#my_form input[type="file"]');
$.each(inputs, function(obj, v) {
var file = v.files[0];
var filename = $(v).attr("data-filename");
var name = $(v).attr("id");
myFormData.append(name, file, filename);
});
var inputs = $('#my_form input[type="text"]');
$.each(inputs, function(obj, v) {
var name = $(v).attr("id");
var value = $(v).val();
myFormData.append(name, value);
});
var xhr = new XMLHttpRequest;
xhr.open('POST', '/echo/html/', true);
xhr.send(myFormData);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my_form" enctype="multipart/form-data">
<input type="file" name="file_1" id="file_1" data-filename="image.jpg"><br />
<input type="text" name="check1" id="check1"/><br />
<input type="text" name="check2" id="check2"/><br />
<input type="text" name="check3" id="check3"/><br />
<button>Submit</button>
</form>
Let me know if it not works.
i have file upload form field,i select one gif','png' ,'jpg' means it will work,and i am select any other file .mp3,.php file it will give error like this **SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 73 of the JSON data**.i want to file type check and file size after that i want to insert the value,but don't know how to do this,i think my PHP code should be wrong...
<?php
$filename = basename($_FILES['file']['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new_name= md5($filename.time()).'.'.$extension;
if (move_uploaded_file($_FILES['file']['tmp_name'], "horoscope/".$new_name)) {
// FILE TYPE CHECKING
$allowed = array('gif','png' ,'jpg');
if(!in_array($extension,$allowed) ) {
$newuser = array('photoname' => $new_name, "message" => "error");
if($_FILES['file']['size'] > 2459681 ){
$newuser = array('photoname' => $new_name, "message" => "filesize is to large");
}else{
$newuser = array('photoname' => $new_name, "message" => "success");
}
echo json_encode($newuser);
}
else{
$newuser = array('photoname' => $new_name, "message" => "success");
}
echo json_encode($newuser);
}else{
//echo "Error";
$newuser = array("message" => "file is not moving");
echo json_encode($newuser);
}
?>
<script type="text/javascript">
$(document).ready(function(){
$("#user-submit").click(function(event){
event.preventDefault();
if($("form#newUserForm").valid()){
var formData = new FormData();
var formData = new FormData($('#newUserForm')[0]);
formData.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'horoscope-check.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
var res=jQuery.parseJSON(data);// convert the json
console.log(res);
},
});
return false;
}else{
console.log("false");
}
});
});
</script>
<form class="form-horizontal form-bordered" method="POST" id="newUserForm" enctype="multipart/form-data">
<div class="form-group">
<label class="col-md-3 control-label">Photo Upload</label>
<div class="col-md-6">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input">
<i class="fa fa-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div>
<span class="btn btn-default btn-file">
<span class="fileupload-exists">Change</span>
<span class="fileupload-new">Select file</span>
<input type="file" id="file" name="file" value="" aria-required="true" required="" data-msg-required="Please select your file">
</span>
Remove
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button class="btn btn-info" type="submit" id="user-submit">Submit</button>
</div>
</div>
</form>
Using xhr() could solve your problem... for example :-
var formData = new FormData($('#newUserForm')[0]);
$.ajax({
url: 'horoscope-check.php',
type: 'POST',
data: formData,
async: false,
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
//if you want progress report otherwise you can remove this part from here to
myXhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100 ;
percentComplete = Math.round(percentComplete);
$("#progress").text(percentComplete + " %");
}
}, false);
//here
return myXhr;
},
cache: false,
contentType: false,
processData: false,
success: function (data) {
var res=jQuery.parseJSON(data);// convert the json
console.log(res);
},
});