Laravel 8: AJAX Upload files using onchange - javascript

I want to upload multiple files using onchange in laravel 8. is it possible to upload just by onchange? I have this html form. I hope you can help me guys. thanks
<form method="POST" enctype="multipart/form-data" id="upload_form">
#csrf
<input type="file" name="file[]" id="file" multiple >
</form>
this is my Jquery and Ajax Script.
<script>
function uploadfile(){
var formData = new FormData($('#upload_form')[0]);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type:'POST',
url: "{{ route('dropzone-action') }}",
data: formData,
contentType: false,
processData: false,
success: (response) => {
if (response) {
this.reset();
alert('Image has been uploaded successfully');
}
},
error: function(response){
console.log(response);
$('#image-input-error').text(response.responseJSON.errors.file);
}
});
}
and here is my controller
function action(Request $request){
$request->validate([
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if($request->hasFile('file')){
foreach($request->file as $file) {
$completeFileName = $file->getClientOriginalName();
$fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME);
$extension = $file->getClientOriginalExtension();
$file->storeAs('uploads', $completeFileName);
}
}
return response()->json('Image uploaded successfully');
}

You can call change method
$("#file").change(function() {
uploadfile();
});
and in validation
$request->validate([
'file.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
and in controller
function action(Request $request){
$request->validate([
'file.*' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
foreach($request->file as $file) {
if($file!=null){
$completeFileName = $file->getClientOriginalName();
$fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME);
$extension = $file->getClientOriginalExtension();
$file->storeAs('uploads', $completeFileName);
}
}
return response()->json('Image uploaded successfully');
}

Related

CodeIgniter file upload error “You did not select a file to upload” using Ajax

I've seen and tried a few answers that are similar to this question, but it still displays the same error.
The console is also giving the error: Uncaught TypeError: Cannot read property 'length' of undefined at Function.each (jquery-1.10.2.js:631)
My view:
<form action="https://dev.vmc.w3.uvm.edu/xana/sensors/deployments" class="basicForm aboutForm form-horizontal" id="deploymentForm" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div class="form-group">
<label for="fldFileName" class="col-sm-4 control-label">Image</label>
<div class="col-sm-8">
<input type="file" name="fldFileName" value="" class="form-control" id="fldFileName" />
</div>
</div>
<button type="button" class="btn btn-primary" id="newSensorSubmit">Save</button>
</form>
javascript to submit form:
$(document).on("click", "#newSensorSubmit", function(event){
var posturl="<?php echo site_url("sensors/add_deployment");?>";
var formData = new FormData();
var fldFileName = $('#fldFileName').val();
formData.append('fldFileName', fldFileName);
jQuery.ajax({
url: posturl,
data: formData,
cache: false,
mimeType: "multipart/form-data",
dataType: 'json',
contentType: false,
processData: false,
type: 'POST',
success: function(data){
if(data.status === 'success') {
//handle success
}
else {
//handle fail
}
},
error: (error) => {
$('#articleErrorText').html(JSON.stringify(error));
}
});
});
controller:
public function add_deployment(){
$this->load->helper(array('form', 'url'));
$this->load->library('upload');
$config = array(
'upload_path' => site_url("attachments/project/999/metstations"),
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "16000000"
);
$this->load->library('upload', $config);
if($this->upload->do_upload('fldFileName'))
{
$data['image_metadata'] = array('image_metadata' => $this->upload->data());
}
else
{
$error = $this->upload->display_errors();
$data['errors']='<p class="error-message">'.$error.'</p>';
$data['status']='failure';
}
}
Try This.
To get all your form inputs, including the type="file" you need to use FormData object.
To append param just use append() method:
formData.append("param", "value");
And in the php-side I catch it:
echo $file_name = ($_FILES['file']['name']);
View Code:-
<body>
<p id="msg"></p>
<input type="file" id="file" name="file" />
<button id="upload">Upload</button>
</body>
jQuery / Ajax Code:-
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e){
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'ControllerName/upload_file', // 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) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
</script>
Controller Code:-
class ControllerName extends CI_Controller {
function __construct() {
parent::__construct();
}
function upload_file() {
//upload file
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = '*';
$config['max_filename'] = '255';
$config['encrypt_name'] = TRUE; // remove it for actual file name.
$config['max_size'] = '1024'; //1 MB
if (isset($_FILES['file']['name'])) {
if (0 < $_FILES['file']['error']) {
echo 'Error during file upload' . $_FILES['file']['error'];
} else {
if (file_exists('uploads/' . $_FILES['file']['name'])) {
echo 'File already exists : uploads/' . $_FILES['file']['name'];
} else {
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
echo $this->upload->display_errors();
} else {
echo 'File successfully uploaded : uploads/' . $_FILES['file']['name'];
}
}
}
} else {
echo 'Please choose a file';
}
}
}
Note:- For more reference regarding this check this
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

jQuery File Upload and put Filename in Database

I have this AJAX message form:
HTML:
<form class="" id="message-form" action="message-send.php" method="POST">
<div class="form-group">
<textarea name="message" id="message-field" rows="3" class="form-control message-field"></textarea>
</div>
<div class="form-group">
<input type="file" id="file" name="file">
</div>
<div class="form-group text-right">
<input type="submit" id="submit" class="btn btn-success btn-sm msg-send" value="Envoyer" disabled>
</div>
</form>
JavaScript:
var message_form = $('#message-form');
message_form.submit(function (e) {
e.preventDefault();
$('#submit').attr('disabled', true).val('Sending...');
$.ajax({
type: message_form.attr('method'),
url: message_form.attr('action'),
data: message_form.serialize(),
success: function (data) {
console.log('Submission was successful.');
console.log(data);
$('#message-field').val('');
$('#submit').val('Send');
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
});
PHP:
require 'config.php';
$message = $_POST['message'];
$query = 'INSERT INTO messages (time, from, to, message, file) VALUES (?, ?, ?, ?, ?)';
if (!($stmt = $mysqli->prepare($query))) {
echo $mysqli->error;
}
$stmt->bind_param('iiiss', $time, $from, $to, $message, $file);
$stmt->execute();
$stmt->close();
$mysqli->close();
Now what I need:
Upload the file using AJAX
Store the file as is to "/uploads/" with the same name
Put the filename in the db with the message
NB: The form already works well (The code presented is just a minimal version) I just need the handling of the file.
You have not included mimetypes in your ajax request.
mimeTypes: "multipart/form-data" add this inside ajax
try sending input values with formdata
var message_form = $('#message-form');
message_form.submit(function (e) {
e.preventDefault();
$('#submit').attr('disabled', true).val('Sending...');
var message_form = $('#message-form');
var file = $('#file');
var formdata = new FormData();
formdata.append('file', file.files[0]);
formdata.append('message', $('#message-field').val());
$.ajax({
type: message_form.attr('method'),
url: message_form.attr('action'),
mimeTypes: "multipart/form-data,
data: formdata,
async: true,
contentType: false,
processData: false,
beforeSend: function(){
},
success: function (data) {
console.log('Submission was successful.');
console.log(data);
$('#message-field').val('');
$('#submit').val('Send');
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
}

Ajax script not function

I have a request with ajax that still loads the php script instead of performing its function without refreshing. Am guessing there is an issue with my ajax Below is anything wrong with the ajax script
HTML
<form action='connect_exec.php' method='post' id='connect_form' enctype='multipart/form-data'>
<input type='text' name='conn_id' id='conn_id' value='$ad_id'>
<input type='submit' name='connect' class='conn_text' id='connect' value='connect +'>
</form>
Ajax request
$('#connect_form').submit(function(e) {
e.preventDefault();
var ad_id = $('#conn_id').val();
$.ajax({
type: "POST",
url: "connect_exec.php",
data: ad_id
}).done(function(response) {
console.log(response);
}).fail(function(data) {
console.log(data);
});
});
PHP SCRIPT
require_once("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['connect'])) {
$my_id = $_SESSION['log_id'];
$ad_id = $_POST['conn_id'];
$rand_num = rand();
$hsql = <<<EOF
SELECT COUNT(hash) as count FROM connect WHERE(user_one = '$my_id'
AND user_two = '$ad_id') OR(user_one = '$ad_id'
AND user_two = '$my_id');
EOF;
$hret = $db->querySingle($hsql);
if ($hret == 1) {
$response = "Your are already connected to '$ad_id'";
} else {
$csql = <<<EOF
INSERT INTO connect(user_one, user_two, hash) VALUES('$my_id', '$ad_id', '$rand_num');
EOF;
$cret = $db - > exec($csql);
if (!$cret) {
echo "Error connecting to '$ad_id'";
} else {
echo "Successful";
}
}
}
The form executes but not without refreshing the page. Please what is the issue with the ajax?
I recommend you to send form data serialized, using serialize() method.
Also, use submit event for form: $('form').on('submit', function (e) {}
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "connect_exec.php",
data: $('form').serialize()
}).done(function(response) {
console.log(response);
}).fail(function(data) {
console.log(data);
});
});
$('#connect').click(function(e) {
e.preventDefault();
var ad_id = $('#conn_id').val();
console.log(ad_id);
$.ajax({
type: "POST",
url: "connect_exec.php",
data: ad_id
})
.done(function (response) {
console.log(response);
})
.fail(function (data) {
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action='connect_exec.php' method='post' id='connect_form' enctype='multipart/form-data'>
<input type='text' name='conn_id' id='conn_id' />
<input onclick="return;" type='submit' name='connect' class='conn_text' id='connect' value='connect +'>
</form>

Can't upload files above 1mb in Dropzone

I used Dropzone to handle the file uploads in my Symfony2 project.
It's working fine if I upload files below 1mb but when I upload a file exceeding 1mb, it throws an exception.
I thought the problem was on the maxFilesize config of Dropzone but it wasn't. It was working since it shows a message that the file size exceeds the max size that I've set.
My form:
<form id="quickUpload" action="{{ path('upload_process') }}" method="put" enctype="multipart/form-data" class="dropzone">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
Javascript:
Dropzone.options.quickUpload = {
addRemoveLinks: true,
dictDefaultMessage: "Drop files to upload (or click)",
maxFilesize: 5,
init: function () {
this.on("success", function (file, response) {
file.serverId = response.id;
});
this.on("removedfile", function (file) {
if (!file.serverId) {
return;
}
var url = "{{ path("delete_upload") }}";
$.ajax({
url: url,
type: 'POST',
data: {id: file.serverId},
dataType: 'json',
success: function (data) {
console.log("File Deleted");
},
error: function () {
console.log("File Delete Error");
}
});
});
}
}
Controller:
/**
* #Route("/upload_process", name="upload_process")
* #Method("PUT")
*/
public function uploadProcessAction(Request $request) {
if ($request->isXmlHttpRequest()) {
$files = $request->files;
$em = $this->getDoctrine()->getManager();
$ids = [];
foreach ($files as $file) {
$document = new Document();
$document->setUploader($this->getUser())
->setFile($file);
$em->persist($document);
$ids[] = $document;
}
$em->flush();
return new JsonResponse(['id' => $ids[0]->getId()]);
}
}
Finally fixed it. I just needed to change the value of the upload_max_filesize in my php.ini file. I saved the file, restarted XAMPP and got it working.

upload image using formdata ajax send to php

I newbie in this webpage area and I was try to upload image to my file by using ajax and send it to php. But I have done some coding here. Can some one correct me where I'am wrong ?
here is my form with file upload and a button
<form method="post" enctype="multipart/form-data" action="">
<input type="file" name="images" id="images" multiple="" />
<input type="submit" value="submit" id="harlo">
</form>
Once I click on button the file will send it here and receive the src and ajax to php file
but I guess is about getting source problem. Need some one correct it for me.
(function upload() {
var input2 = document.getElementById("harlo"),
formdata = false;
if (window.FormData) {
formdata = new FormData();
}
input2.addEventListener("click", function () {
var i = 0, len = $('input[type="file"]')[0].files;
for ( ; i < len.length; i++ ) {
file = len.files[i];
if (formdata) {
formdata.append("images", file);
}
}
if (formdata) {
$.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
}
});
}
}, false);
}());
<?php
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "uploads/" . $_FILES['images']['name'][$key]);
}
}
echo "<h2>Successfully Uploaded Images</h2>";
?>
Use something like:
$("form").on("submit", function(
// Your ajax request goes here
$.ajax({
url: "upload.php",
type: "POST",
data: $("form").serialize(),
processData: false,
contentType: false,
success: function (res) {
$("#response").innerHTML = res;
}
});
return false;
));
But there seems to be a problem with sending files trough ajax anyway. Cause they're missed by the serialize() method because JS has no access to files content on users computer. So the form must be sent to the server to get the file data.
See here: https://stackoverflow.com/a/4545089/1652031

Categories

Resources