I am using laravel framework 5.2. I have successfully implemented dropzone and i have also done with upload images. Now problem is that when i want to delete the image from folder it gives me error. I think my code is not right for deleting image.
Here is my add Upload image Function i have uploaded images in session:-
public function addContributorimages(Request $request){
if($request->ajax()){
$image=$_FILES['file'];
if(!empty($image)){
if($image['error']==0){
$name = pathinfo($_FILES['file']['name']);
$ext = $name['extension'];
$rand=str_random(24).'.'.$ext;
$destination = base_path() . '/public/images/ContributorImages/';
if(is_uploaded_file($image['tmp_name'])){
list( $width, $height, $source_type ) = getimagesize($image['tmp_name']);
if ($width >= 10 && $height >= 10){
move_uploaded_file($image['tmp_name'],$destination.$rand);
$request->session()->put('contributorimage.'.str_random(5).'.image',$rand);
$images = $request->session()->get('contributorimage');
echo "<pre>"; print_r($images);
}
else{
echo "Error";die;
}
}
}
}
}
}
This is my add Function of images
Here is my dropzone code :-
Dropzone.autoDiscover = false;
var fileList = new Array;
var i =0;
$("#my-awesome-dropzone").dropzone({
method:'POST',
maxFiles: 10,
paramName: "file",
maxFilesize: 10,
addRemoveLinks: true,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
clickable: true,
init: function() {
// Hack: Add the dropzone class to the element
$(this.element).addClass("dropzone");
this.on("sending",function(file, xhr, formData) {
formData.append("_token", "{{ csrf_token() }}");
});
this.on("success", function(file, serverFileName) {
fileList[i] = {"serverFileName" : serverFileName, "fileName" : file.name,"fileId" : i };
//console.log(fileList);
i++;
});
this.on("removedfile", function(file) {
var rmvFile = "";
for(f=0;f<fileList.length;f++){
if(fileList[f].fileName == file.name)
{
rmvFile = fileList[f].serverFileName;
if (rmvFile){
$.ajax({
type: 'POST',
url: '../contributor/delete-subimages/'+rmvFile,
});
}
}
}
});
},
url: '../contributor/add-subimages',
});
});
My images are successfully uploaded but i want to remove the image from session as well as from folder can anyone help me how to do that
Here is my delete function of image:-
public function deleteContributorImage(Request $request,$name = null){
$imageName=explode('.',$name);
$imageRandomName = $request->session()->get('contributorimage.'.$imageName[0].'.image');
$destination = base_path() . '/public/images/ContributorImages/';
if(unlink($destination.$imageRandomName)){
$request->session()->forget('contributorimage.'.$imageName[0]);
echo "success";
}
else{
echo "failed";
}
}
Now when i upload images it create this sesssion now i am having two images in session
Array
(
[Dkf08] => Array
(
[image] => whywu3dprVPKKkhUgdIMAdLQ.jpg
)
[rH5NV] => Array
(
[image] => i2sZEqjMdiQHcKRyy5Km9vlu.jpg
)
)
can anyone hlep me how to slove this issue . Thanks in advance :)
you have to create one hidden filed for that and when you remove file from dropzone than that file name should be save in that hidden filed.
myDropzone.on('removedfile', function (file) {
var hidden_filed= document.getElementById('hidden_filed').value;
if (alreadyRemove == "") {
$('#deleteImage').val(file.name);
} else {
$('#deleteImage').val(hidden_filed+ ',' + file.name);
}
});
after that get that field as POST data in controller. From file name you can delete Image as usual.
Related
I am using ajax to send a request to a laravel controller with multiple images and other,
Everything work on local environement but when I upload to the production environement, the upload fails with the error
Failed to load resource:/property/images/add:1 the server responded with a status of 403 ()
Here is the ajax code
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('input[name=_token]').val()}
});
$('#images').change(function () {
event.preventDefault();
let image_upload = new FormData();
let TotalImages = $('#images')[0].files.length; //Total Images
let images = $('#images')[0];
let p_id = $('input[name=p_id]').val();
for (let i = 0; i < TotalImages; i++) {
image_upload.append('images[]', images.files[i]);
}
image_upload.append('TotalImages', TotalImages);
image_upload.append('p_id', p_id);
$.ajax({
method: 'POST',
url: '{{ route('image.add') }}',
data: image_upload,
contentType: false,
processData: false,
success: function (images) {
Swal.fire(
'Success!',
'Images uploaded successfully',
'success'
);
$('#images').reset();
},
error: function () {
Swal.fire(
'Failed!',
'An error occured please try again',
'error'
);
$('#images').reset();
}
});
});
and this is the controller code
public function store(Request $request)
{
//check if an image has been selected
if ($request->images) {
$total=$request->TotalImages;
$images = $request->images;
foreach($images as $image) {
$photo = new Photo;
$photo->p_id = $request->p_id;
$image_temp = $image;
//echo $image_temp; die;
if ($image_temp->isValid()) {
$extension = $image_temp->getClientOriginalExtension();
$filename = 'bks'.mt_rand(000, 9999999999) . '.' . $extension;
$filepath = 'uploads/property/large/' . $filename;
$webimagefilepath = 'uploads/property/small/' . $filename;
//upload the image
Image::make($image_temp)->resize(600, 600)->save($filepath);
Image::make($image_temp)->resize(200, 200)->save($webimagefilepath);
$photo->path = $filename;
$photo->alt_text = "Book sasa property image";
$photo->save();
}
}
}
return response()->json("Success");
}
I am using named routes and the name is the one used in the ajax url.
What could I be doing wrong and how can I solve it?
Okay so I have an uploader script that I customized and it works great. I have 2 more steps that I need to do for it to be complete and it is beyond my scope and I have read and tried numerous things and still am not getting the results that I want.
Again only code that is releative to my issue will be posted as the code works perfect and does not need any changing with the exception of trying to get a value from AJAX to PHP.
FULL JS FILE BELOW:
jQuery(document).ready(function () {
var img_zone = document.getElementById('img-zone'),
collect = {
filereader: typeof FileReader != 'undefined',
zone: 'draggable' in document.createElement('span'),
formdata: !!window.FormData
},
acceptedTypes = {
'image/png': true,
'image/jpeg': true,
'image/jpg': true,
'image/gif': true
};
// Function to show messages
function ajax_msg(status, msg) {
var the_msg = '<div class="alert alert-'+ (status ? 'success' : 'danger') +'">';
the_msg += '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>';
the_msg += msg;
the_msg += '</div>';
$(the_msg).insertBefore(img_zone);
}
// Function to upload image through AJAX
function ajax_upload(files) {
$('.progress').removeClass('hidden');
$('.progress-bar').css({ "width": "0%" });
$('.progress-bar span').html('0% complete');
var productTestID = "333746240";
var formData = new FormData(this);
formData.append('productTestID',productTestID);
//formData.append('any_var', 'any value');
for (var i = 0; i < files.length; i++) {
//formData.append('img_file_' + i, files[i]);
formData.append('img_file[]', files[i]);
}
$.ajax({
url : "upload.php", // Change name according to your php script to handle uploading on server
type : 'post',
data : formData,
dataType : 'json',
processData: false,
contentType: false,
error : function(request){
ajax_msg(false, 'An error has occured while uploading photo.');
},
success : function(json){
var img_preview = $('#img-preview');
var col = '.col-sm-2';
$('.progress').addClass('hidden');
var photos = $('<div class="photos"></div>');
$(photos).html(json.img);
var lt = $(col, photos).length;
$('col', photos).hide();
$(img_preview).prepend(photos.html());
$(col + ':lt('+lt+')', img_preview).fadeIn(2000);
if(json.error != '')
ajax_msg(false, json.error);
},
progress: function(e) {
if(e.lengthComputable) {
var pct = (e.loaded / e.total) * 100;
$('.progress-bar').css({ "width": pct + "%" });
$('.progress-bar span').html(pct + '% complete');
}
else {
console.warn('Content Length not reported!');
}
}
});
}
// Call AJAX upload function on drag and drop event
function dragHandle(element) {
element.ondragover = function () { return false; };
element.ondragend = function () { return false; };
element.ondrop = function (e) {
e.preventDefault();
ajax_upload(e.dataTransfer.files);
}
}
if (collect.zone) {
dragHandle(img_zone);
}
else {
alert("Drag & Drop isn't supported, use Open File Browser to upload photos.");
}
// Call AJAX upload function on image selection using file browser button
$(document).on('change', '.btn-file :file', function() {
ajax_upload(this.files);
});
// File upload progress event listener
(function($, window, undefined) {
var hasOnProgress = ("onprogress" in $.ajaxSettings.xhr());
if (!hasOnProgress) {
return;
}
var oldXHR = $.ajaxSettings.xhr;
$.ajaxSettings.xhr = function() {
var xhr = oldXHR();
if(xhr instanceof window.XMLHttpRequest) {
xhr.addEventListener('progress', this.progress, false);
}
if(xhr.upload) {
xhr.upload.addEventListener('progress', this.progress, false);
}
return xhr;
};
})(jQuery, window);
});
So the above code is from the .js file. The script uploads multiple selected files, which works fine. From what I have read, in order to get additional values sent to PHP you have to use the .append(), which is what I have done below. I created the var productTestID and gave it a value and then added it to the formData using the append().
My issue is how do I read it in PHP?
I have tried $_POST[productTestID] and get no results at all. I even tried doing an isset() and it comes back not set.
So what do I need to do in my PHP code to read or extract that value? Below is an excerpt from my upload.php file and like I said the file uploads work and this is how they are being accessed.
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$error = '';
$img = '';
$dir = dirname($_SERVER['SCRIPT_FILENAME'])."/". DIR_WS_IMAGES . "upload/";
$extensions = array("jpeg","jpg","png");
foreach($_FILES['img_file']['tmp_name'] as $key => $tmp_name )
Further down in my upload.php file:
//MOVE TO FINAL LOCATION
$uploaded_file = $dir.$file_name;
if (rename($uploaded_file, $uniqueFileName))
{
$productTestID = $_POST['productTestID'];
}
$img .= '<div class="col-sm-2"><div class="thumbnail">';
$img .= '<img src="'.$dir.$file_name.'" />'.$uploaded_file . '<br>' .$fileName.'<br>'.$uniqueFileName.'<br>This Product Id is:';
$img .= $productTestID;
$img .= '</div></div>';
}
Thank You,
Shawn Mulligan
In the PHP file, image details are not displaying. but in js file formdata is consoled proper.
How to pass image details to php file using fetch and formdata?
I have run this in macOS.
This is Demo.js file for uploading image in folder and store name in phpmyadmin.
import * as React from "react";
import { Button, Image, View } from "react-native";
import * as ImagePicker from "expo-image-picker";
import * as Permissions from "expo-permissions";
import Constants from "expo-constants";
import { ROOT_URL } from "../../get_connection";
export default class Demo extends React.Component {
state = {
image: null,
Image_TAG: ""
};
render() {
let { image } = this.state;
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<Button
title="Pick an image from camera roll"
onPress={this._pickImage}
/>
{image && (
<Image source={{ uri: image }} style={{ width: 200, height: 200 }} />
)}
</View>
);
}
componentDidMount() {
this.getPermissionAsync();
}
getPermissionAsync = async () => {
if (Constants.platform.ios) {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status !== "granted") {
alert("Sorry, we need camera roll permissions to make this work!");
}
}
};
_pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3]
});
console.log(result);
if (result.cancelled) {
return;
}
if (!result.cancelled) {
this.setState({
image: result.uri
});
}
// ImagePicker saves the taken photo to disk and returns a local URI to it
let localUri = result.uri;
let filename = localUri.split("/").pop();
// Infer the type of the image
let match = /\.(\w+)$/.exec(filename);
let type = match ? `image/${match[1]}` : `image`;
var data = new FormData();
data.append("photo", {
image: localUri, // your file path string
image_tag: filename,
type
});
data.append("hh", "bb");
console.log(data);
fetch(`${ROOT_URL}/uploadImage.php`, {
headers: {
Accept: "application/json",
"Content-Type": "multipart/form-data"
},
method: "POST",
body: data
})
.then(response => response.text())
.then(responseJson => {
console.log(responseJson);
alert(responseJson);
})
.catch(error => {
console.error(error);
});
};
}
**This is php servlet file.**
<?php
// Importing DBConfig.php file.
include 'DBConfig.php';
// Creating connection.
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
//$json = file_get_contents('php://input');
// $obj = json_decode($json,true);
// Image uploading folder.
$target_dir = "uploads";
print_r($_POST);
exit;
// Generating random image name each time so image name will not be same .
$target_dir = $target_dir . "/" .rand() . "_" . time() . ".jpeg";
// Receiving image tag sent from application.
$img_tag = $_POST["photo"]["image_tag"];
if($image_tag!=""){
// Receiving image sent from Application
if(move_uploaded_file($_FILES['image']['tmp_name'], $target_dir)){
// Adding domain name with image random name.
$target_dir = $domain_name . $target_dir ;
// Inserting data into MySQL database.
//mysqli_query("insert into image_upload_table (image_tag, image_path) VALUES('$img_tag' , '$target_dir')");
$add = mysqli_query($con,"insert into image_upload_table (image_tag, image_path) VALUES('$img_tag' , '$target_dir')");
if($add){
echo json_encode("Image Uploaded Successfully."); // alert msg in react native
}
else{
echo json_encode('check internet connection'); // our query fail
}
}
}
?>
I expect form data with image details but this is what I got.
enter image description here
enter image description here
I'm using laravel 4.2 and currently I don't how to save a csv file into public\csv\ directory using AJAX. I'm still finding some answers. Maybe someone can help me with this.
Here's my code:
In blade view:
{{Form::open(['route' => 'file_upload', 'files' => true, 'id' => 'upload_form', 'method' => 'POST'])}}
{{Form::file('csv_upload', ['id' => 'uploaded_file', 'accept' => 'text/csv'])}}
{{Form::submit('submit', ['class' => 'btn btn-primary btn-xs', 'id' => 'upload'])}}
{{Form::close()}}
Javascript Ajax:
var ajax_ready = 1
var token = {{Session::get('_token')}}
if($.type(originalOptions.data) === 'string') {
options.data = originalOptions.data+"&_token="+token;
}else if($.type(originalOptions.data) === 'object') {
//Here I got a new error
}else{
options.data = $.param(($.extend(originalOptions.data, {'_token':mmad_token})));
}
options.url = originalOptions.url.slice(0,originalOptions.url.indexOf("?_token="));
if (ajax_ready!=1){
jqXHR.abort();
}
ajax_ready = 0;
});
$('form#upload_form').on('submit', function(e){
e.preventDefault();
var uploadFile = $('#uploaded_file');
var ext = $("input#uploaded_file").val().split(".").pop().toLowerCase();
var file = $('input[name="csv_upload"]').val();
if($.inArray(ext, ["csv"]) === -1) {
alert("Please upload a .csv file!");
return false;
}
var csv = uploadFile[0].files;
var form = new FormData(this);
var csvFile = {lastModifed: csv[0].lastModified, fileName: csv[0].name, size: csv[0].size, fileType: csv[0].type};
$.post('{{ URL::route("file_upload") }}?_token={{Session::token()}}',{
data: form
}).done(function(response){
});
});
PHP:
public function upload_csv()
{
$inputs = Input::all();
$csvFile = $inputs['data']['fileName'];
$path = public_path().DIRECTORY_SEPARATOR.'csv'.DIRECTORY_SEPARATOR;
$path2 = public_path('csv/');
if(is_dir($path2))
{
#move_uploaded_file($csvFile, $path2.$csvFile); //This line can't move the uploaded files in my desired directory
}
return json_encode(['success' => 1, 'description' => 'Successfully Upload File']);
}
This code below does work when not using AJAX:
if(Input::hasFile('csv_upload'))
{
$file = Input::file('csv_upload');
$originalFilename = $file->getClientOriginalName();
$rules = ['csv_upload' => 'required|file:csv'];
$validate = Validator::make(['csv_upload' => $file], $rules);
if($validate->fails())
{
return json_encode(['error' => 1, 'description' => 'File must be in .csv format']);
}
$path = public_path('/csv/');
if(!file_exists($path))
{
mkdir($path);
}
}
Console.log of csv
You can not move file because when you submit form with ajax file is not being sent with ajax,For sending file you have to send file with FormData() javascript Object.
If you check in upload_csv controller by putting print_r($_FILES); you will get empty array.
So use FormData on client side for appending file, then try agian.
You aren't getting error beacuse you have used php Error Control Operators likes#move_uploaded_file($csvFile, $path2.$csvFile);.
if you need working example then tell me i will give it to you.
Code For Your Help:
1. In blade view:
<script type="text/javascript">
$('form#upload_form').on('submit', function(e){
e.preventDefault();
var uploadFile = $('#uploaded_file');
var ext = $("input#uploaded_file").val().split(".").pop().toLowerCase();
var file = $('input[name="mmad_csv_upload"]').val();
if($.inArray(ext, ["csv"]) === -1) {
alert("Please upload a .csv file!");
return false;
}
var csv = uploadFile[0].files;
var formData = new FormData($(this)[0]);
formData.append('uploaded_file', $("#uploaded_file")[0].files[0]);
formData.append('lastModifed', csv[0].lastModified);
formData.append('fileName', csv[0].name);
console.log(formData);
$.ajax({
url: '{{ URL::route("file_upload") }}',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
success: function (returndata) { //alert(returndata); return false;
}
});
});
</script>
2.Controller
public function file_upload(Request $request)
{
$inputs = Input::all();
$csvFile = $inputs['fileName'];
$path = public_path().DIRECTORY_SEPARATOR.'csv'.DIRECTORY_SEPARATOR;
$path2 = public_path('/csv/');
if(is_dir($path2))
{
$success = $request->file('uploaded_file')->move($path2, $csvFile);
}
return json_encode(['success' => 1, 'description' => 'Successfully Upload File']);
}
To move the uploaded file to a new location, you should use the move method. This method will move the file from its temporary upload location (as determined by your PHP configuration) to a more permanent destination of your choosing:
Input::file('fileName')->move($destinationPath, $fileName);
If you need additional validations, you can check it at http://laravel.com/docs/5.1/requests#files
Default AJAX POST does not support file uploads. Use jQuery Form to upload files successfully. Full documentation of file upload at http://malsup.com/jquery/form/#file-upload
Below my example of a recentlty build script... My Controller uploads the files to S3, but is easy to be implemented with local storage.
var progress = function(event, position, total, percent) {
$(".progress-bar").width(percent + '%');
$(".progress-bar").html(percent + '%');
if(percent > 50) {
$(".progress-bar").css('color','#fff');
}
if(percent == 100) {
setTimeout(function(){
$(".progress").html('<span class="processing-msg">Processing... Please be patient!</span>');
$(".processing-msg").fadeIn('slow');
}, 1000);
}
}
var success = function(data) {
var obj = $.parseJSON(data);
$("#"+obj.hidden, parent.document).val(obj.filename);
var src = 'https://s3.amazonaws.com/spincms'+obj.path+'thumb_'+obj.filename;
$("#uploaded-"+obj.hidden, parent.document).html('<img class="img-circle uploaded-img" src="' + src + '">');
$(".progress").html('<span class="processing-msg-next">File has been uploaded and processed. Do not forget to submit the form!</span>');
}
var options = {
target: '#output',
uploadProgress: progress,
success: success,
resetForm: true
};
$(document).on('click', "#upload-now", function(e) {
$(".progress").html('<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100"></div>');
if($("#upload-form input[type=file]")[0].files.length == 0) {
$(".progress").html('<span class="processing-msg-next">No file selected!</span>');
return false;
} else {
var name = $("#upload-form input[name='name']").val();
var token = $("#upload-form input[name='_token']").val();
var file_name = $("#upload-form input[type=file]")[0].files[0].name;
$("#upload-form").ajaxSubmit(options);
}
}
});
Since you are using jQuery you can use the form plugin as it will make things much more easier for you to work with for example , this is the jquery part that you will use :
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#upload_form').ajaxForm(function() {
alert("Your file has been uploaded, thanks");
});
});
and in your controller you can code it like :
pubilc function postUpload()
{
$success = false;
if(Request::ajax())
{
if(Input::hasFile('csv_upload'))
{
$file = Input::file('csv_upload');
if(!File::isDirectory(storage_path('csv'))) {
File::createDirectory(storage_path('csv'));
}
$file->move(storage_path('csv'), $file->getClientOriginalName());
// now your file is on app/storage/csv folder
$filePath = storage_path('csv/'.$file->getClientOriginalName());
$success = true;
}
}
return Response::json(['success'=>$success]);
}
I am currently using Dropzone to allow users upload some files into the system I'm developing and have linked the Dropzone to a div within my form,
But once the upload is complete, I would like the filename of the newly uploaded file to be returned to the Dropzone as a hidden form input so that I can save the filename in the database.
Below is the code Im using:
$(document).ready(function(){
var myDropzone = new Dropzone("div#my-awesome-dropzone", {
url: "?content=plg_dropzone&folder=php&file=uploadhandler&alert=yes",
addRemoveLinks : true,
acceptedFiles : "application/pdf",
maxFilesize: 5, // MB
maxFiles: 5
});
});
Assistance on this will be greatly appreciated. I've searched on the net and not gotten a solution.
Thanks
Thanks to #edwin Krause giving the first hint for me on this. But because I needed to do another search on it to actually replace the source of the preview I add my finding here for others not knowing exactly how to do it.
success: function( file, response ) {
file.previewElement.querySelector("img").src = response;
}
My PHP script is echoing the name of the cropped image which has been uploaded as plain HTML if you returning JSON your success callback could look like this
success: function( file, response ) {
obj = JSON.parse(response);
file.previewElement.querySelector("img").src = obj.src;
}
Or version of the code which works in Dropzone.js 5.7.2 (July 23rd 2020) is:
success: function( file, response ) {
file.previewElement.querySelector("img").src = response.src;
}
Notice: obj.src or response.src - src has to match your json property of course.
You could even replace the whole file.previewElement with your server response
I believe using the success callback and a JSON response from the server is the best way to do it? This works great for me, Hope that helps (fileupload_flag I'm using to prevent form submission before upload is completed)
My Dropzone config:
Dropzone.options.myAvatarDropzone = {
maxFilesize: 3, // MB
maxFiles: 1,
addRemoveLinks: true,
init: function() {
this.on("addedfile", function(file) { fileupload_flag = 1; });
this.on("complete", function(file) { fileupload_flag = 0; });
},
accept: function(file, done)
{
var re = /(?:\.([^.]+))?$/;
var ext = re.exec(file.name)[1];
ext = ext.toUpperCase();
if ( ext == "JPG" || ext == "JPEG" || ext == "PNG" || ext == "GIF" || ext == "BMP")
{
done();
}else {
done("Please select only supported picture files.");
}
},
success: function( file, response ){
obj = JSON.parse(response);
alert(obj.filename); // <---- here is your filename
}
};
My server response:
$upload_success = $file->move($pubpath.$foldername, $filename);
$success_message = array( 'success' => 200,
'filename' => $pubpath.$foldername.'/'.$filename,
);
if( $upload_success ) {
return json_encode($success_message);
} else {
return Response::json('error', 400);
}
Keep an array and add file names to it in accept function. After successful upload, you
var arFiles = [];
var myDropzone = new Dropzone("form#myDropzone", {
url: someurl,
uploadMultiple: true,
accept: function(file, done) {
var extension = file.name.substring(file.name.lastIndexOf('.')+1);
//console.log("extension - " + extension + ", arExistingFiles - " + arExistingFiles);
if (extension == "exe" || extension == "bat") {
done("Error! File(s) of these type(s) are not accepted.");
} else if(jQuery.inArray(file.name, arExistingFiles) > -1) {
arErrorFiles.push(file.name);
done("File already exists.");
}else { done(); arFiles.push(file.name) }
},
})
console.log("arFiles --> " + arFiles);
OR
Maintain a global List on server side where the uploading is done and then you can send it to database.