I'am using dropzone js to upload multiple images (dropzone programmatically).
Upload files, it's ok.
But when I remove a file, some error occurred:
500 Internal Server Error (Method App\Modules\Product\Controllers\ProductController::delete does not exist - I don't have delete() method in controller - why?).
Cannot read property 'removeChild' of null
My route
Route::post('/adminks/products/delete/dropzone', 'ProductController#deleteImageDropzone')->name('be.delete.dropzone');
My Controller
public function deleteImageDropzone(Request $request) {
$image = $request->filename;
ProductImage::where(['image_name' => $image, 'model' => 'Product', 'module' => 'Product'])->delete();
$path = public_path().'/uploads/images/product/product/'.$image;
if (file_exists($path)) {
unlink($path);
}
return $image;
}
My JS
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("div#dropzone_images", {
url: "{{ route('be.upload.dropzone') }}",
sending: function (file, xhr, formData) {
formData.append('_token', $('meta[name="csrf-token"]').attr('content'));
var code = '{{ $code }}';
formData.append('code', code);
},
paramName: 'others_image',
addRemoveLinks: true,
acceptedFiles: '.jpeg,.jpg,.png,.gif',
dictRemoveFile: 'Xóa ảnh',
init: function() {
this.on("removedfile", function(file) {
var name = file.upload.filename;
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
},
type: 'POST',
url: '{{ url('/adminks/products/delete/dropzone') }}',
data: { filename: name },
success: function (data){
console.log("File has been successfully removed!!");
},
error: function(e) {
console.log(e);
}});
var fileRef;
return (fileRef = file.previewElement) != null ?
fileRef.parentNode.removeChild(file.previewElement) : void 0;
});
}
});
Any solution? All comments are respected!
Thanks so much!
Related
Please help. I have this jQuery code
$('.modal-footer').on('click', '.edit', function() {
var serializedData = $(".form-horizontal").serialize();
var criscore = new Array();
$('input[name^=criscore]').each(function(){
criscore.push({score:$(this).val(), criid:$(this).data('criid')});
});
for (var key in criscore) {
var score = criscore[key].score;
var criid = criscore[key].criid;
//console.log(score +" s "+ criid);
$.ajax({
method: 'post',
url: '/judges/candidates/scorecandidates',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {
'_token': $('input[name=_token]').val(),
'canId': $('input[name=canId]').val(),
'catId': $('input[name=catId]').val(),
'criId': criid,
'score': score,
'judgeId': $('input[name=judgeId]').val()
},
success: function(data) {
console.log(data);
}
});
}
});
and in my controller is
public function scorecandidates(Request $req)
{
$data = new Score();
$data->canId = $req->canId;
$data->catId = $req->catId;
$data->criId = $req->criId;
$data->score = $req->score;
$data->judgeId = $req->judgeId;
$data->save();
return response()->json($data);
}
my problem is that it is still keeps having an 500 (Internal Server Error)
Even though I already put the csrf token is different ways.. Can any body help me?
Thank you
This is my Ajax call :
$("#cover-input").change(function(){
var file_data = $("#cover-input").prop("files")[0];
var form_data = new FormData();
form_data.append("cover_file", file_data);
//kaherdin
$.ajax({
url: 'update-cover',
type: 'POST',
dataType: 'script',
data: form_data,
contentType: false,
processData: false,
async: false,
success: function(resp){
console.log(resp);
},
error: function(err){
console.log('Likes error', err);
}
});
readURL_cover(this);
});
I've a function that basicly trim and upload a file on change.
public function updateCover(Request $request) {
$user = Sentinel::check();
$destinationPath = public_path('uploads/users');
if ($fileCover = $request->file('cover_file')) {
$input_cover = time().'.'.$fileCover->getClientOriginalExtension();
$img = Image::make($fileCover->getRealPath());
$img->fit(1920, 555, function ($constraint) {
$constraint->aspectRatio();
})->save($destinationPath.'/'.$input_cover);
// $user->cover = $input_cover;
$response = $input_cover;
return $response;
}
But this get me an error. I just want to get "input_cover" back to my ajax call so I can show the updated picture.
If I change : $response = $input_cover to $response = [$input_cover]; it kinkds of work but the input is like : ["my_pic.jpg"] so it's not nice.
You should return a JsonResponse like so:
return response()->json(['input_cover' => $input_cover]);
Check this for responses in json and how they work https://laravel.com/docs/5.4/responses#json-responses
I'm trying to upload multiple files from a drag/drop event using jQuery/AJAX/Laravel.
MY DROP EVENT:
$( document ).on('drop dragleave', '.file-drag', function(e){
$(this).removeClass('drop-ready');
if(e.originalEvent.dataTransfer.files.length) {
e.preventDefault();
e.stopPropagation();
if (e.type === "drop") {
var files = e.originalEvent.dataTransfer.files;
AjaxFileUpload(files)
}
}
});
MY UPLOAD SCRIPT:
function AjaxFileUpload(files){
console.log(files);
//Start appending the files to the FormData object.
var formData = new FormData;
formData.append('_token', CSRF_TOKEN);
for(var i = 0; i < files.length; i++){
formData.append(files[i].name, files[i])
}
console.log(formData.entries());
$.ajax({
//Server script/controller to process the upload
url: 'upload',
type: 'POST',
// Form data
data: formData,
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Error logging
error: function(jqXHR, textStatus, errorThrown){
console.log(JSON.stringify(jqXHR));
console.log('AJAX Error: ' + textStatus + ": " + errorThrown);
},
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
} , false);
}
return myXhr;
},
success: function(data){
console.log(data);
}
});
}
MY CONTROLLER CODE:
class UploadsController extends Controller
{
public function UploadFiles(Request $request){
return $request->all();
}
}
I THINK my images are getting to the server side, as when I return the request object, I get the following in console:
Thus, the CSRF token is getting through, and the images (I think?) are getting through. My problem from here is accessing the files with PHP and storing them via ->store();.
In the countless examples online/documentation, they typically use something along the lines of:
$path = $request->photo->store('images');
However, I don't understand the 'photo' aspect of this. What if a video or a PDF is uploaded? I basically don't understand how I am to access the different parts of the request object. Documentation on Laravel site is pretty sparse for this and only gives an example using 'photo' of which it never explains.
Figured it out.
In my uploadscontroller:
class UploadsController extends Controller
{
public function UploadFiles(Request $request){
$arr = [];
foreach($request->all() as $file){
if(is_file($file)){
$string = str_random(16);
$ext = $file->guessExtension();
$file_name = $string . '.' . $ext;
$filepath = 'uploads/' . Auth::user()->username . '/' . $file_name;
$file->storeAs(('uploads/' . Auth::user()->username), $file_name);
array_push($arr, [$file_name, $filepath]);
}
}
return $arr;
}
}
This took me a while but I finally got a working solution. I'm using Dropzone so the list of file objects is returned by getAcceptedFiles() but it should be the same concept for you. I'm also attaching the files to an existing form.
Upload:
var formElement = document.getElementById("addForm");
var formData = new FormData(formElement);
// Attach uploaded files to form submission
var files = myDZ.getAcceptedFiles(); // using Dropzone
for (var i = files.length - 1; i >= 0; i--) {
formData.append('files[]', files[i]);
}
$.ajax({
url: 'home/',
data: formData,
processData: false,
contentType: false,
timeout: 1000,
type: 'POST',
headers: {
'X-CSRF-TOKEN': Laravel.csrfToken,
},
success: function(){
...
},
error: function (jqXHR, textStatus) {
...
}
});
Controller:
foreach($request->only('files') as $files){
foreach ($files as $file) {
if(is_file($file)) { // not sure this is needed
$fname = $file->getClientOriginalName();
$fpath = $file->store('docs'); // path to file
}
}
}
Dropzone Script:
Dropzone.autoDiscover = false;
var myDZ = new Dropzone("#my-dropzone", {
url: "/home/files",
maxFilesize: 5,
maxFiles: 5,
addRemoveLinks: true,
dictDefaultMessage: 'Drop files here or click to upload <br> (max: 5 files)',
headers: {
'X-CSRF-TOKEN': Laravel.csrfToken
},
});
Regarding the examples found in Laravel's documentation, 'photo' is simply making use of a magic method to reference a file uploaded with a name of 'photo'. You can replace 'photo' with whatever your specific file names is/are. Specific functions capable of being called on your uploaded files can be found here.
I have used dropzone.js for uploading multiple files. once uploaded i am getting the reponse from php file and have to update the filename in dropzone so that the file can be deleted immediately. other than that i need to refresh the page and delete the image.
How to achieve it?
This is my code. I am using dropzone.js plugin to add multiple file upload
php file
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$fileName = $_FILES['file']['name'];
$targetPath = APPPATH . 'uploads/work_picture/';
$targetFile = $targetPath . time().$fileName ;
move_uploaded_file($tempFile, $targetFile);
// if you want to save in db,where here
// with out model just for example
// $this->load->database(); // load database
$this->db->insert('tablename',array('business_id'=>$business_id->id,'picture_name' => time().$fileName));
header('Content-type: text/json'); //3
header('Content-type: application/json');
echo json_encode(array("name"=>time().$fileName));
exit;
}
<form action="<?php echo site_url('settings_pro/work_picture_upload'); ?>" class="dropzone dz-clickable" id="my-awesome-dropzone"><div class="dz-default dz-message"><span>Drop Files Here or Click to Upload...</span></div></form>
Dropzone.options.myAwesomeDropzone = {
addRemoveLinks: true ,
maxFiles: 5,
acceptedFiles: 'image/*',
url: "<?php echo site_url('settings_pro/work_picture_upload'); ?>",
init: function() {
thisDropzone = this;
this.on("maxfilesexceeded", function(file){
alert("No more files please!");
this.removeFile(file);
this.addFile(file);
});
this.on('removedfile', function(file) {
console.log(file);
var file_name = file.name;
$.ajax({
type: 'POST',
url: '<?php echo base_url('settings_pro/delete_image'); ?>',
data: { 'filename': file_name },
success: function(report) {
console.log(report);
},
error: function(report) {
console.log(report);
}
});
});
$.get('<?php echo base_url('settings_pro/get_picture'); ?>', function(data) {
$.each(data, function(key,value){
//alert(data);
//var mockFile = { name: value.name, size: value.size };
var mockFile = { name: value.name};
thisDropzone.options.addedfile.call(thisDropzone, mockFile);
thisDropzone.options.thumbnail.call(thisDropzone, mockFile,
value.path);
});
});
this.on("successmultiple", function(files, response) {
alert("hi");
// event when files are successfully uploaded
// you can return a response string and process it here through 'response'
});
this.on("success", function(file, response) {
file.serverId = response;
//$('#dz-preview').html('<img src="" width="200" height="200" alt="<?php //echo $empNameFull; ?>">');
// location.reload();
});
You can try with code might be helpful.
Dropzone.options.myAwesomeDropzone = {
init: function(){
var th = this;
this.on('queuecomplete', function(){
ImageUpload.loadImage(); // CALL IMAGE LOADING HERE
setTimeout(function(){
th.removeAllFiles();
},5000);
})
},
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 2, // MB
acceptedFiles: 'image/*',
};
my.on("complete", function(file) { my.removeFile(file); });
my.on("complete", function(file) { my.removeAllFiles(file);});
I tried to upload a file via api to server.
function uploadUsing$http(file) {
file.upload = Upload.http({
url: 'api/upload' + $scope.getReqParams(),
method: 'POST',
headers: {
'Content-Type': file.type
},
data: file
});
file.upload.then(function (response) {
file.result = response.data;
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
file.upload.progress(function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
If console.log(file), there is image data, but when i send the request to server i get an empty array.
server function:
public function uploadAPI(Request $request)
{
$image = $request->file('file');
dd($image); ---------> return []/null
return response()->json('upload hit server');
}
What's the problem here? Thanks!!
Have you tried using
Upload.upload({
url: 'upload/url',
data: {file: file, 'param1': $scope.param1}
});
Instead?