File upload via Ajax in Laravel - javascript

I'm trying to upload a file through ajax in Laravel.
$("#stepbutton2").click(function(){
var uploadFile = document.getElementById("largeImage");
if( ""==uploadFile.value){
}
else{
var fd = new FormData();
fd.append( "fileInput", $("#largeImage")[0].files[0]);
$.ajax({
url: '/nominations/upload/image',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
if(data.uploaded==true){
alert(data.url);
}
},
error: function(err){
alert(err);
}
});
}
});
I'm passing the file input to the php script.
public function image(){
$file = Input::file('fileInput');
$ext = $file->getClientOriginalExtension();
$fileName = md5(time()).".$ext";
$destinationPath = "uploads/".date('Y').'/'.date('m').'/';
$file->move($destinationPath, $fileName);
$path = $file->getRealPath();
return Response::json(["success"=>true,"uploaded"=>true, "url"=>$path]);
}
I'm getting a the response as
{"success":true,"uploaded":true,"url":false}
The request Payload is
------WebKitFormBoundary30GMDJXOsygjL0ZS
Content-Disposition: form-data; name="fileInput"; filename="DSC06065 copy.jpg"
Content-Type: image/jpeg
Why this is happening?

Found the answer:
public function image(){
$file = Input::file('fileInput');
$ext = $file->getClientOriginalExtension();
$fileName = md5(time()).".$ext";
$destinationPath = "uploads/".date('Y').'/'.date('m').'/';
$moved_file = $file->move($destinationPath, $fileName);
$path = $moved_file->getRealPath();
return Response::json(["success"=>true,"uploaded"=>true, "url"=>$path]);
}
Get the path after assigning it to a new variable.

Related

How to upload an image to server directory using ajax?

I have this ajax post to the server to send some data to an SQL db :
$.ajax({
method: "POST",
url: "https://www.example.com/main/public/actions.php",
data: {
name: person.name,
age: person.age,
height: person.height,
weight: person.weight
},
success: function (response) {
console.log(response)
}
})
in the server i get this data with php like this :
<?php
include "config.php";
if(isset ( $_REQUEST["name"] ) ) {
$name = $_REQUEST["name"];
$age = $_REQUEST["age"];
$height = $_REQUEST["height"];
$weight = $_REQUEST["weight"];
$sql = "INSERT INTO persons ( name, age, height, weight )
VALUES ( '$name', '$age', '$height', '$weight' )";
if ($conn->query($sql) === TRUE) {
echo "New person stored succesfully !";
exit;
}else {
echo "Error: " . $sql . "<br>" . $conn->error;
exit;
}
};
?>
I also have this input :
<input id="myFileInput" type="file" accept="image/*">
and in the same directory as actions.php i have the folder /images
How can i include an image ( from #myFileInput ) in this ajax post and save it to the server using the same query in php ?
I have searched solutions in SO but most of them are >10 years old,i was wondering if there is a simple and modern method to do it,i'm open to learn and use the fetch api if its the best practice.
You should use the formData API to send your file (https://developer.mozilla.org/fr/docs/Web/API/FormData/FormData)
I think what you are looking for is something like that:
var file_data = $('#myFileInput').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'https://www.example.com/main/public/actions.php',
contentType: false,
processData: false, // Important to keep file as is
data: form_data,
type: 'POST',
success: function(php_script_response){
console.log(response);
}
});
jQuery ajax wrapper has a parameter to avoid content processing which is important for file upload.
On the server side, a vrey simple handler for files could look like this:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'];
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
via ajax FormData you can send it . refer here . Note : data: new FormData(this) - This sends the entire form data (incldues file and input box data)
URL : https://www.cloudways.com/blog/the-basics-of-file-upload-in-php/
$(document).ready(function(e) {
$("#form").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "ajaxupload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data) {
if (data == 'invalid') {
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
} else {
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e) {
$("#err").html(e).fadeIn();
}
});
}));
});
If you are not averse to using the fetch api then you might be able to send the textual data and your file like this:
let file=document.querySelector('#myFileInput').files[0];
let fd=new FormData();
fd.set('name',person.name);
fd.set('age',person.age);
fd.set('height',person.height);
fd.set('weight',person.weight);
fd.set('file', file, file.name );
let args={// edit as appropriate for domain and whether to send cookies
body:fd,
mode:'same-origin',
method:'post',
credentials:'same-origin'
};
let url='https://www.example.com/main/public/actions.php';
let oReq=new Request( url, args );
fetch( oReq )
.then( r=>r.text() )
.then( text=>{
console.log(text)
});
And on the PHP side you should use a prepared statement to mitigate SQL injection and should be able to access the uploaded file like so:
<?php
if( isset(
$_POST['name'],
$_POST['age'],
$_POST['height'],
$_POST['weight'],
$_FILES['file']
)) {
include 'config.php';
$name = $_POST['name'];
$age = $_POST['age'];
$height = $_POST['height'];
$weight = $_POST['weight'];
$obj=(object)$_FILES['file'];
$name=$obj->name;
$tmp=$obj->tmp_name;
move_uploaded_file($tmp,'/path/to/folder/'.$name );
#add file name to db????
$sql = 'INSERT INTO `persons` ( `name`, `age`, `height`, `weight` ) VALUES ( ?,?,?,? )';
$stmt=$conn->prepare($sql);
$stmt->bind_param('ssss',$name,$age,$height,$weight);
$stmt->execute();
$rows=$stmt->affected_rows;
$stmt->close();
$conn->close();
exit( $rows ? 'New person stored succesfully!' : 'Bogus...');
};
?>

Symfony 4.4 - Summernote editor upload base64 images to server

Pretty common problem with a lot of answers here but couldn't make it work for my Symfony 4 application. I tried to debug my action with dump() and die(), it doesn't even enter the action and I think that's why my images won't upload.
My JavaScript code in Twig:
<script>
var url = "{{ path('editor_file_upload') }}";
$(document).ready(function() {
$('.summernote').summernote({
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0], editor, welEditable);
}
});
function sendFile(file, editor, welEditable) {
let formData = new FormData();
formData.append("file", file);
$.ajax({
data: formData,
type: "POST",
url: url,
cache: false,
contentType: false,
processData: false,
success: function(url) {
editor.insertImage(welEditable, url);
}
});
}
});
</script>
My Controller action:
/**
* #Route("/editor-file-upload", name="editor_file_upload")
*/
public function uploadEditorFile(Request $request)
{
/** #var UploadedFile $File */
$File = $request->files->get('file');
if ($File) {
$originalFilename = pathinfo($File->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
$newFilename = $safeFilename . '-' . uniqid() . '.' . $File->guessExtension();
try {
$File->move(
$this->getParameter('editor_images'),
$newFilename
);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
}
}
The problem was that I didn't return any response, here's the edit:
/**
* #Route("/upload-editor", name="admin_upload_editor")
*/
public function uploadEditorFile(Request $request, KernelInterface $kernel) {
/** #var UploadedFile $file */
$file = $request->files->get('img');
if (empty($file))
{
return new Response("No file",Response::HTTP_UNPROCESSABLE_ENTITY, ['content-type' => 'text/plain']);
}
if ($file) {
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
$newFilename = $safeFilename . '-' . uniqid() . '.' . $file->guessExtension();
try {
$file->move(
$kernel->getProjectDir() . '/' .
$this->getParameter('public_dir') . '/' .
$this->getParameter('editor_dir'),
$newFilename
);
return new Response("/editor_images/" . $newFilename, Response::HTTP_OK);
} catch (FileException $e) {
return new Response("Cannot upload file!",Response::HTTP_UNPROCESSABLE_ENTITY, ['content-type' => 'text/plain']);
}
}
}

Save image from blob-url (javascript / php)

With pdf-js I filter images of an PDF-File. After this I display all of the images in a div. The elements look like this:
<img src="blob:http://myhost/07eee62c-8632-4d7f-a086-c06f1c920808">
What I want to do, is to save all of this images in a server's directory. But I don't know how to do this.
i tried this, but I think it's totally wrong:
let form_data = new FormData();
fetch(url)
.then(res => res.blob()) // Gets the response and returns it as a blob
.then(blob => {
// Here's where you get access to the blob
// And you can use it for whatever you want
// Like calling ref().put(blob)
// Here, I use it to make an image appear on the page
let objectURL = URL.createObjectURL(blob);
let myImage = new Image();
myImage.src = objectURL;
console.log(id, url, selectedProject, pdfName);
form_data.append('file', myImage);
form_data.append('path', dest);
form_data.append('project', selectedProject);
form_data.append('url', url);
});
$.ajax({
url: 'upload_referenceFile.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (php_script_response) {
}
});
php:
$project = $_REQUEST['project'];
$script = $_REQUEST['path'];
$dest = 'data/' . $project . '/' . $script . '/media/';
_log($_REQUEST['file']);
$exists = file_exists($dest . $_FILES['file']['name']);
if($exists){
}else{
if (!file_exists($dest)) {
if (!mkdir($dest, 0777, true) && !is_dir($dest)) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $dest));
}
}
move_uploaded_file($_FILES['file']['tmp_name'], $dest . $_FILES['file']['name']);
}

ajax passing two forms with codeigniter

I have a problem related with passing two forms in ajax to my controller code igniter. My first form is a file var formData = new FormData($('#form-upload')[0]);
and my second form consists of profile data $('#frm_patientreg').serialize()
now my problem is how can I pass these two forms in ajax?
I already tried this code:
var fileToUpload = inputFile[0].files[0];
if(fileToUpload != 'undefine') {
var formData = new FormData($('#form-upload')[0]);
$.ajax({
type: "POST",
url: siteurl+"sec_myclinic/addpatient",
data: $('#frm_patientreg').serialize()+formData,
processData: false,
contentType: false,
success: function(msg) {
alert("Successfully Added");
$('#frm_patientreg')[0].reset();
}
});
}
else {
alert("No File Selected");
}
but it returns me an error.
When I tried to pass data:formData, only, my image file was successfully uploaded, but when I add the $('#frm_patientreg').serialize(), it outputs an error. How can I pass both forms?
Here is my controller:
public function addpatient() {
$config['upload_path'] = './asset/uploaded_images/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 1024 * 8;
$this->load->library('upload', $config);
if($this->upload->do_upload("file")) {
$upload_data = $this->upload->data();
$file_name = base_url().'asset/uploaded_images/'.$upload_data['file_name'];
$mypatiendid = $this->genpatient_id();
$patient_bday = $this->input->post('pabdate');
$DB_date = date('Y-m-d', strtotime($patient_bday));
$patient_height = $this->input->post('paheight');
$DB_height = $patient_height . " cm";
$patient_weight = $this->input->post('paweight');
$DB_weight = $patient_weight . " kg";
$data = array (
'patient_id' => $mypatiendid,
'patient_fname' => $this->input->post('pafname'),
'patient_mname' => $this->input->post('pamname'),
'patient_lname' => $this->input->post('palname'),
'patient_address' => $this->input->post('paaddress'),
'patient_contact_info' => $this->input->post('pacontact'),
'patient_bday' => $DB_date,
'patient_age' => $this->input->post('paage'),
'patient_height' => $DB_height,
'patient_weight' => $DB_weight,
'patient_sex' => $this->input->post('psex'),
'patient_civil_status' => $this->input->post('pmartialstat'),
'patient_photo' => $file_name,
);
var_dump($data);
}
else {
echo "File cannot be uploaded";
$error = array('error' => $this->upload->display_errors()); var_dump($error);
}
}
Not tested..but try this:
var FormTwo = new FormData();
$('#frm_patientreg input, #frm_patientreg select').each(function(index){
FormTwo.append($(this).attr('name'),$(this).val());
});
FormTwo.append('file', $('#frm_patientreg input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
url: siteurl+"sec_myclinic/addpatient",
data: {formTwo: FormTwo, formOne: formData},
processData: false,
contentType: false,
success: function(msg) {
alert("Successfully Added");
$('#frm_patientreg')[0].reset();
}
});
change this
data: $('#frm_patientreg').serialize()+formData,
into this
data: $('#frm_patientreg').serialize()+'&'+formData,

Ajax File Upload - Script Writes garbage in File

i have a Problem with my Ajax-Fileupload Script.
When I upload my Files, the Files are corrupt. When I open the File with Notepad++, i see that there are for example the following Lines:
-----------------------------22998260013704
Content-Disposition: form-data; name="0"; filename="myimage.png"
Content-Type: image/png
filecontent
-----------------------------22998260013704--
When I delete the 3 Lines bevor filecontent und the Line after filecontent, the File is ok.
I have no clue, why these 4 Lines are written to the Files.
I hope that somebody can help me.
Here is my Javascript-Code:
var myFiles = [];
function ajaxFileUpload() {
var dataid = document.getElementById("dataid").getAttribute("data-id"),
data = new FormData(),
maxSize = 100.0,
file = null,
myUrl = "xxx/save";
$.each(myFiles, function(key, value) {
console.log(key+" "+value);
file = value;
data.append(key, value);
});
var filesize = file.size;
if ((filesize/(1024*1024)) <= maxSize) {
$.ajax({
type: "PUT", //<-- http://stackoverflow.com/questions/10475313/ajax-file-upload-with-xmlhttprequest
url: myUrl,
processData: false,
contentType: false,
data: data,
beforeSend: function(xhr) {
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-myid", dataid);
},
success: function (json) {
//....
},
});
} else {
//...
}
}
And here my relevant PHP-Code:
private function copyPutFilesToTmp($directory = "") {
$temp = "xxx";
if (!is_dir($temp)) {
mkdir ($temp, 0777, true);
}
$tmpPath = $temp."/";
$filename = $_SERVER['HTTP_X_FILE_NAME'];
$in = fopen('php://input', 'r');
$ziel = $tmpPath.$filename;
if (!file_exists($ziel)) {
$fileuploadok = true;
$out = fopen($ziel, 'w');
$data = fread($in, 1024);
while($data) {
if ($data != false) {
fwrite($out, $data);
} else {
$fileuploadok = false;
}
$data = fread($in, 1024);
}
fclose($in);
fclose($out);
if ($fileuploadok === FALSE) {
//...
} else {
//...
}
} else {
//...
}
return $answer;
}
I found the problem.
if I sent the file directly as data and not within a FormData it works!
So the right Code is:
var myFiles = [];
function ajaxFileUpload() {
var dataid = document.getElementById("dataid").getAttribute("data-id"),
maxSize = 100.0,
file = null,
myUrl = "xxx/save";
$.each(myFiles, function(key, value) {
file = value;
});
var filesize = file.size;
if ((filesize/(1024*1024)) <= maxSize) {
$.ajax({
type: "PUT", //<-- https://stackoverflow.com/questions/10475313/ajax-file-upload-with-xmlhttprequest
url: myUrl,
processData: false,
contentType: false,
data: file,
beforeSend: function(xhr) {
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-myid", dataid);
},
success: function (json) {
//....
},
});
} else {
//...
}
}
found here: AJAX File Upload with XMLHttpRequest

Categories

Resources