Dropzone.js - Laravel | 500 Internal Server Error - javascript

I want to upload my images with dropzone.js, I get images on server side, its ok. But When I want to try save, it gives 500 internal server error.
Dropzone.options.mDropzoneTwo = {
paramName: "file", // The name that will be used to transfer the file
maxFiles: 10,
maxFilesize: 10, // MB
url: 'images/save' ,
method: 'POST',
headers: {
"X-CSRF-TOKEN": document.head.querySelector("[name=csrf-token]").content
},
uploadMultiple: true,
accept: function(file, done) {
done();
},
success: function () {
console.log()
}
};
And here is my controller. I'm saving images to public/uploads folder.
$realname = str_slug(pathinfo($request->file('file')->getClientOriginalName(), PATHINFO_FILENAME));
$extension = $request->file('file')->getClientOriginalExtension();
$new_name = $realname."-".time().".".$extension;
$request->file('file')->move(public_path('uploads/'.str_slug($new_name)));
$image = new Media();
$image->image = str_slug($new_name);
$image->image_path = "images/".str_slug($new_name);
$image->image_alt_name = $realname;
$image->save();

As per comments --
It means your application is not getting file object on $request->file('file') this, you can get more info by printing $request and then you can check for file too weather its being sent from client script or not

Related

Issue in grapesJS - Asset manager handling

I'm now working on grapesJS implementation in our application. I have gone through documents provided & some of the issues reported regarding the asset manager in Github, etc.. I was not able to show the list of uploaded images in the Asset manager after a hard refresh list disappears.
I have tried to upload files to AmazonS3, upload was ok & I get its response, also it is showing in the list. In this case, I was not able to edit images due to the CORS issue.
Later, I tried with the base64 encoded image. With this method, I was able to edit uploaded images. Also got it in the image listing. As I said earlier, the image list only available until a hard refresh. I think it is from the cache.
I have doubts in a few codes, can you help me out of it.
Here is the assetManager section code:
assetManager: {
storageType : '',
storeOnChange : true,
storeAfterUpload : true,
embedAsBase64 : true, // Make this false to upload image to AmazonS3
upload : siteURL+'assets/CONTENT/img', // For temporary storage, Upload endpoint, set `false` to disable upload
assets : [],
// headers: {}, // Custom headers to pass with the upload request
// params: {}, // Custom parameters to pass with the upload request, eg. csrf token
credentials: 'include', // The credentials setting for the upload request, eg. 'include', 'omit'
autoAdd : 1, // If true, tries to add automatically uploaded assets.
dropzone : 0, // Enable an upload dropzone on the entire editor (not document) when dragging files over it
openAssetsOnDrop : 1, // Open the asset manager once files are been dropped via the dropzone
multiUpload : true, // Allow uploading multiple files per request. If disabled filename will not have '[]' appended
showUrlInput: true, // Toggles visiblity of assets url input
uploadFile: function(e) {
// Ref: https://blog.webnersolutions.com/adding-image-upload-feature-in-grapesjs-editor/
var files = e.dataTransfer ? e.dataTransfer.files : e.target.files;
var formData = new FormData();
for(var i in files){
formData.append('file-'+i, files[i]); // Containing all the selected images from local
}
$.ajax({
url: siteURL + 'uploadImage_base64', // Save image as base64 encoded - Its a function
// url: siteURL + 'uploadImage', // Upload image to AmazonS3 - Its a function
type: 'POST',
data: formData,
contentType: false,
crossDomain: true,
dataType: 'json',
mimeType: "multipart/form-data",
processData: false,
success: function(result) {
var myJSON = [];
if ((typeof(result['data']) != 'undefined') && (result != 'null')) {
$.each(result['data'], function(key, value) {
myJSON[key] = value;
});
console.log(myJSON);
// while using base64 encode => 0: {name: "ipsumImage.png", type: "image", src: "data:image/png;base64,iVBORw0KGgAAVwA…AAAAAAAAAAAAAAAD4Pv4B6rBPej6tvioAAAAASUVORK5CYII=", height: 145, width: 348}
// while using AmazonS3 => 0: {name: "logo_sigclub.png", type: "image", src: "https://amazonaws.com/assets/CONTENT/img/logo_sigclub.png", status: true, message: "Uploaded successfully", …}
editor.AssetManager.add(myJSON); //adding images to asset manager of GrapesJS
}
}
});
}
}
I have doubt in:
upload : siteURL+'assets/CONTENT/img', is this image upload path or a function which uploads image?
If I'm using AmazonS3, can I able to get the editing option with the CORS issue?
How can I show the uploaded images in Asset Manager without disappearing later?

How do you upload a single image with Dropzone.js?

Dropzone.js seems to be uploading images as multi-part form data. How do I get it to upload images in the same way an image upload would work with cURL or a binary image upload with Postman?
I'm getting a pre-signed URL for S3 from a server. The pre-singed URL allows an image upload, but not form fields:
var myDropzone = new Dropzone("#photo-dropzone");
myDropzone.options.autoProcessQueue = false;
myDropzone.options.autoDiscover = false;
myDropzone.options.method = "PUT";
myDropzone.on("addedfile", function ( file) {
console.log("Photo dropped: " + file.name );
console.log("Do presign URL: " + doPresignUrl);
$.post( doPresignUrl, { photoName: file.name, description: "Image of something" })
.done(function( data ) {
myDropzone.options.url = data.url
console.log(data.url);
myDropzone.processQueue();
});
});
If I use the returned URL with Postman and set the body to binary and attach the image, then the upload works fine. However, if the Dropzone library uses the same URL to upload the image to S3 then I get a 403 because S3 does not expect form fields.
Update:
An Ajax alternative works as below with a S3 signed url, but Dropzone.js does not seem willing to put the raw image data in the PUT message body.
$.ajax( {
url: data.url,
type: 'PUT',
data: file,
processData: false,
contentType: false,
headers: {'Content-Type': 'multipart/form-data'},
success: function(){
console.log( "File was uploaded" );
}
});
Set maxFiles to 1.
Dropzone.autoDiscover = false;
dzAllocationFiles = new Dropzone("div#file-container", {
url: "api.php?do=uploadFiles"
, autoDiscover: false
, maxFiles: 1
, autoQueue: true
, addRemoveLinks: true
, acceptedFiles: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
});
dzAllocationFiles.on("success", function (file, response) {
// Success Operations
});
dzAllocationFiles.on("maxfilesexceeded", function (file, response) {
allocationFileNames = [];
this.removeAllFiles();
this.addFile(file);
});
Add below options, then working.
myDropzone.options.sending = function(file, xhr) {
var _send = xhr.send;
xhr.send = function() {
_send.call(xhr, file);
}
}

Dropzone stops on the progress bar

This will be hard to explain, because I have no live demo. I use a simple dropzone.
HTML:
<form action="http://localhost/upload.php" class="dropzone" method="post" id="upload-widget"></form>
JavaScript:
Dropzone.options.uploadWidget = {
uploadMultiple: false,
maxFilesize: 2, // MB
maxFiles: 1,
acceptedFiles: 'image/*',
init: function() {
this.on('success', function() {
alert('OK);
});
}
};
upload.php file:
if(!empty($_FILES)){
$targetDir = "uploads/";
$fileName = $_FILES['file']['name'];
$targetFile = $targetDir.$fileName;
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile)){
//insert file information into db table
}
}
When I pick or drop a file, it will upload, but stops at the progress:
I have no idea, why. When I upload any file, file appear in the /uploads/ folder, but seems like dropzone.js doesn't react on complete. Do I need to print some data? I used this website as tutorial http://www.codexworld.com/drag-and-drop-file-upload-using-dropzone-php/
I found the problem. I'm using this PHP debugger: https://github.com/JosephLenton/PHP-Error which for some unknown reasons disabled receiving XHTTP responses (funny that my website is almost whole in ajax and I haven't noticed any error). Anyway, I can't use dropzone.js with this debugger. I can live with that (also it is turned off when it will go to production).
Try to use the success event like that :
Dropzone.options.uploadWidget = {
uploadMultiple: false,
maxFilesize: 2, // MB
maxFiles: 1,
acceptedFiles: 'image/*',
success: function(file, res) {
console.log('Upload success.');
console.log(res);
},
error: function(file, res) {
console.log('Upload error.');
console.log(res);
}
};

504 Error with jQuery File Upload?

I am using the API for blueimp's jQuery File Upload plugin to upload large and small files to S3. I am sending a PUT request to the server, which handles the S3 uploading. My code is below:
// Initialize the file upload so we don't get errors
angular.element(document.querySelector('#add-file-btn')).fileupload({
url: '/test'
});
// Set up options for file upload
angular.element(document.querySelector('#add-file-btn')).fileupload(
'option',
{
url: '/temp', // Temporary, replaced in handleAdd
type: 'PUT',
dataType: 'json',
dropZone: 'dropzone-area',
acceptFileTypes: /(\.|\/)(csv|jpe?g|png)$/i, // Only accept csv files (images enabled for testing)
progressInterval: 2000, // Check progress every 2 seconds
autoUpload: true,
paramName: 'files',
formData: {
fileSize: null
},
beforeSend: function(xhr, data) {
// Set request headers
xhr.setRequestHeader('Authorization', 'bearer ' + storageService.get('token'));
xhr.setRequestHeader('Accept', 'application/json ');
},
multipart: true,
add: handleAdd,
submit: handleSubmit,
progress: handleProgress ,
processdone: handleProcessDone,
processfail: handleProcessFail,
start: handleStart,
stop: handleStop,
done: handleDone
}
);
When I upload a small file (200 KB) the file is successfully uploaded. When I try to upload a large file (2.66 GB) and log the progress shown in my handleProgress() function, I see that the progress hangs for several minutes, then it rapidly logs the last of the progress, so that right after it is 100% complete I see a 504 Gateway Timeout error has been returned.
function handleProgress(e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
data.files[0].progress = progress;
console.log(progress)
}
The backend guy says his code works for uploading large files via the command line so we're trying to figure out why it's not also working from the browser. Any ideas? I know the 504 error is supposed to be just a server-side problem but it's confusing that it's working for the CLI...

Dropzone.js - How to add new property to file object after uploading file

I'm using dropzone and PHP to upload and delete files. When I load my upload page I create some mockfiles with the following params: name, size, thumbnail and id. This mock is set using pre uploaded data.
So when someone click on remove file button, I call the php method that delete the image.
My problem is when the user uploads an file and tries to delete it without loading the page. When it happens, dropzone file object just can't be altered.
I'm trying:
var dropZone3 = new Dropzone("#file3",{
init: function() {
this.on('success', function (file) {
console.log(file);
file['test'] = 'test';
file.test = 'test';
console.log(file);
})
},
paramName: 'file3',
autoProcessQueue:true,
uploadMultiple: false,
parallelUploads: 1,
maxFiles: 3,
maxFilesize: 5,
addRemoveLinks: true
My problem is that the first console.log and the second one inside init on success function shows me the same file.
Anyone knows how to fix it?
Thank you in advance.
It's possible to add properties directly to file object (dropzone v4.3.0)
var dropZone = new Dropzone(document.querySelector('.js-dropzone'), {
url: '/file/upload'
});
dropZone.on('success', function (file, response) {
var res = JSON.parse(response);
if (res.result == true) {
file.test = 'test';
file.id = res.id;
}
});
Don't think you can add a property to the file object when is already uploaded, but you can add it before on the accept property:
var dropZone3 = new Dropzone("#file3", {
url: "upload.php",
init: function () {
this.on('success', function (file) {
console.log(file);
})
},
accept: function(file, done) {
file.test = "test";
return done();
},
paramName: 'file3',
autoProcessQueue: true,
uploadMultiple: false,
parallelUploads: 1,
maxFiles: 3,
maxFilesize: 5,
addRemoveLinks: true
});

Categories

Resources