Uppy + Laravel can't upload file - laravel

Trying to use Uppy JS lib to upload file throug Laravel. Setted up simple upload form with there params:
const options = {
endpoint: '/parts/image-upload',
headers: {
'X-XSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
};
uppyDashboard.use(XHRUpload, options);
And on the backend I'm getting
Illuminate\Contracts\Encryption\DecryptException: The payload is invalid. in file /Users/rd/Projects/xxx/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php on line 195
It's like Laravel trying to decrypt something what is already decrypted, anyway I'm in dead end.

You can this code
var uppy = new Uppy.Core({
// debug: (...args) => console.debug(`[Uppy] [${getTimeStamp()}]`, ...args),
// warn: (...args) => console.warn(`[Uppy] [${getTimeStamp()}]`, ...args),
// error: (...args) => console.error(`[Uppy] [${getTimeStamp()}]`, ...args),
autoProceed: true,
restrictions: {
maxFileSize: 2000000,
maxNumberOfFiles: 10,
minNumberOfFiles: 1,
allowedFileTypes: ['image/*']
}
});
uppy.use(Uppy.Dashboard, {
target: ".UppyDragDrop",
inline: true,
showLinkToFileUploadResult: false,
showProgressDetails: true,
hideCancelButton: true,
hidePauseResumeButton: true,
hideUploadButton: true,
proudlyDisplayPoweredByUppy: false,
locale: {} });

Here's how I implemented it
<script type="text/javascript">
$(document).ready(function() {
$('[id*=drag-drop-area]').each(function(){
var listing_id = $(this).attr('class');
var uppy = new Uppy.Core({
allowMultipleUploadBatches: true,
restrictions: {
maxFileSize: 100000000,
// maxNumberOfFiles: 8,
minNumberOfFiles: 1,
allowedFileTypes: ['image/*', '.jpg', '.jpeg', '.png']
}
})
.use(Uppy.Dashboard, {
inline: true,
target: "#"+$(this).attr('id')+""
})
.use(Uppy.XHRUpload, {
endpoint: 'upload',
formData: true,
bundle: true,
headers: {
'X-CSRF-Token': " {{ csrf_token() }} "
},
});
uppy.on('upload-success', (file, response) => {
response.body.data.forEach(function (item, index) {
console.log(listing_id);
var token =
$('meta[name="csrftoken"]').attr('content');
$.ajax({
url: 'attach',
type: 'POST',
data: { '_token' : token, item, listing_id},
success: function(response)
{
console.log('Updated');
},
error:function (e) {
console.log(e);
}
});
});
window.location.reload();
});
});
});
</script>
You create the endpoint which is the route name and attach at
endpoint: ""
Then you return a response which you grab and do whatever on the last section.
uppy.on('upload-success', (file, response) => {
response.body.data.forEach(function (item, index) {
console.log(listing_id);
var token =
$('meta[name="csrftoken"]').attr('content');
$.ajax({
url: 'attach',
type: 'POST',
data: { '_token' : token, item, listing_id},
success: function(response)
{
console.log('Updated');
},
error:function (e) {
console.log(e);
}
});
});
window.location.reload();
});
I hope this helps

Related

How to set ajax global event to false when using Bloodhound

i am using typeahead for autocomplete.The following code is working fine.
var employees = new Bloodhound({
datumTokenizer: function (d) { return Bloodhound.tokenizers.whitespace(d.name); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
addOnBlur: true,
remote: {
url: $url + '?name=%QUERY',
global: false,
wildcard: '%QUERY',
filter: function (response) {
return $.map(response.results, function (employee) {
return {
mark: employee.MARK,
actitle: employee.ACCOUNTTITLE,
code: employee.CODE
}
});
}
}
});
employees.initialize();
$($classname).typeahead({ highlight: true, minLength: 1, limit: 5 }, {
name: 'employees', displayKey: 'mark', source: employees.ttAdapter(), global: false
})
.on("typeahead:selected", function (obj, company1) {
//debugger;
$($retField).val(company1.actitle);
$($cField).val(company1.code);
})
.on('focusout', function (obj, company) {
//debugger;
$($classname).trigger("typeahead:first-child");
});
}
i want to set ajax global event to false.
Please help me to solve the issue
Late to the party but I figured it out. Use the transport property:
var employees = new Bloodhound({
datumTokenizer: function(d) {
return Bloodhound.tokenizers.whitespace(d.name);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
addOnBlur: true,
remote: {
url: $url + '?name=%QUERY',
global: false,
wildcard: '%QUERY',
transport: function(opts, onSuccess, onError) {
var url = opts.url.split("#")[0];
var query = opts.url.split("#")[1];
$.ajax({
url: url,
data: "search=" + query,
type: "POST",
success: onSuccess,
error: onError,
global: false
})
}
filter: function(response) {
return $.map(response.results, function(employee) {
return {
mark: employee.MARK,
actitle: employee.ACCOUNTTITLE,
code: employee.CODE
}
});
}
}
});
employees.initialize();
Based on this other stackoverflow answer:

vuejs+vue2dropzone call on success

i am quite new in vuejs, so cant find out what am i doing wrong. This is my script part for a vue component:
<script>
export default {
name: 'product-main-info',
components: {
vueDropzone: vue2Dropzone
},
props: {
propId: String,
},
data() {
return {
images: {},
dropzoneOptions: {
url: '/uploadImg',
thumbnailWidth: 150,
maxFilesize: 2.0,
addRemoveLinks: true,
acceptedFiles: ".png,.jpg,.gif,.bmp,.jpeg",
headers: { "X-CSRF-Token": document.head.querySelector('meta[name="csrf-token"]').content },
params: { id: this.propId },
init: function() {
var self = this;
self.on("success", function (file) {
this.$http.get('/getProductImages/' + this.propId)
.then(function(response) {
this.images = response.data;
});
});
}
}
}
},
methods: {
},
created() {
this.$http.get('/getProductImages/' + this.propId)
.then(function(response) {
console.log(response.data);
this.images = response.data;
});
}
}
</script>
I am trying to get new refreshed data after successful image upload, but all i get is:
app.js:16014 Uncaught TypeError: Cannot read property 'get' of undefined
All i need is to refresh my data, but i cant find out how to do this in a right way. Help if possible

AJAX and REST API calls

I am trying to create an AJAX script that will pull data via an API and display it on a page as HTML. Everything using the route below seem to work fine in Postman, but I can't get it to translate in my JS file.
I know I'm calling the URL incorrectly and I'm pretty sure it's because of the :id. I'm not sure how to correct it. I feel like I've tried every URL iteration, but I'm missing something.
// router.REST_VERB('EXPRESS_ROUTE', api.ACTION)
router.get('/', api.list);
router.post('/', api.create);
router.get('/:id', api.read);
router.put('/:id', api.update);
router.get('/delete/:id', api.delete);
Here are my update and delete:
/ AJAX PUT - Update Reminder
function updateReminder(id) {
$.ajax({
type: 'PUT',
url: '/api/',
data: JSON.stringify({
'id': $('#editId').val(),
'name': $('#name').val(),
'occasion': $('#occasion').val(),
'lastgift': $('#lastgift').val()
}),
success: (item) => {
document.location.href="/";
},
contentType: "application/json",
dataType: 'json'
});
}
// AJAX DELETE request - Delete Reminder
function deleteReminder(id) {
$.ajax({
type: 'DELETE',
url: '/api',
data: JSON.stringify({
'id': id
}),
success: (item) => {
document.location.href="/delete";
},
contentType: "application/json",
dataType: 'json'
});
}
EDIT
Here is the controller code for update and delete:
ApiController.update = (req, res) => {
reminderService.update(
req.params.id,
{
name: req.body.name,
occasion: req.body.occasion,
lastgift: req.body.lastgift,
prefgift: req.body.prefgift
},
{new: true}
)
.then((item) => {
res.json(item);
})
.catch((err) => {
if (err) console.log(err);
});
};
ApiController.delete = (req, res) => {
reminderService.delete(req.params.id)
.then((item) => {
res.json(item);
})
.catch((err) => {
if (err) {
res.end("Didn't delete")
}
});
};
and here is the service code:
ReminderService.update = (id, reminderObj) => {
return Reminder.findByIdAndUpdate(
id,
{
$set: reminderObj
},
{
new: true
}
)
.then((item) => {
return item;
})
.catch((err) => {
if (err) {
res.end("You're in reminderService!")
}
});
};
ReminderService.delete = (reminderId) => {
return Reminder.deleteOne({ '_id': reminderId })
.then((item) => {
return item;
})
.catch((err) => {
throw err;
});
};
Your route for delete is wrong, you should use delete instead of get.
router.get('/', api.list);
router.post('/', api.create);
router.get('/:id', api.read);
router.put('/:id', api.update);
router.delete('/:id', api.delete);
In your ajax requests, your url is missing the ids
// AJAX PUT - Update Reminder
function updateReminder(id) {
$.ajax({
type: 'PUT',
url: '/'+id,
data: JSON.stringify({
'id': $('#editId').val(),
'name': $('#name').val(),
'occasion': $('#occasion').val(),
'lastgift': $('#lastgift').val()
}),
success: (item) => {
document.location.href="/";
},
contentType: "application/json",
dataType: 'json'
});
}
// AJAX DELETE request - Delete Reminder
function deleteReminder(id) {
$.ajax({
type: 'DELETE',
url: '/'+id,
data: JSON.stringify({
'id': id
}),
success: (item) => {
document.location.href="/delete";
},
contentType: "application/json",
dataType: 'json'
});
}
One thing I'm skeptical about is that you use JSON.stringify on your data. Does your API specifically require JSON or did you do just do that to try to get it t work?

Dropzonejs: Attempted to redefine property 'filesizeBase'

I've integrated DropzoneJs into a VueJs application im putting together. It's running great in both Chrome and Firefox but for some reason the app is very sad in safari. I'm getting the following error in Safari: Attempted to redefine property 'filesizeBase'.
My Vue Component Looks as Follows:
var Dropzone = require('../../vendor/dropzone.min.js');
module.exports = {
template: require('./views/files.html'),
props: ['files', 'is-complete'],
data: function()
{
return {
reverse: -1,
uploading: false,
token: document.querySelector('#token').getAttribute('value'),
project: document.querySelector('#project').getAttribute('value'),
}
},
methods: {
uploadFile: function(e)
{
e.preventDefault();
var self = this;
this.uploading = !this.uploading;
if(this.uploading)
{
var myDropzone = new Dropzone("form#mediaUpload", {
init: function() {
this.on("complete", function(file) {
setTimeout(function()
{
self.uploading = false;
}, 5000);
});
this.on("success", function(file, uploadedFile) {
self.files.push(uploadedFile);
});
},
paramName: "file",
maxFilesize: 250, // MB
maxFiles: 15,
uploadMultiple: false,
});
}
},
deleteFile: function(file, index)
{
this.files.pop(index);
this.$nextTick(function()
{
this.$http.post('/upload/'+file.id+'/delete');
});
},
},
components: {
fileSize: require('./FileSize'),
humanTime: require('../Helpers/HumanTime'),
mimeType: require('../Helpers/MimeType'),
}
}

How to use ajaxStart if $.ajax method is defined in a class?

I have created ajax method in one class in my js file. Below is enclosed for the reference
var ajaxcall =
{
SitePath: '',
data: '',
url: '',
callbackfunction: '',
fileElementId: '',
AjaxRequest: false,
callback: true,
async: false,
folder: '',
filename: '',
Call: function () {
if (ajaxcall.AjaxRequest == true) {
alert(ajaxcall.AjaxRequest);
return;
}
else {
try {
ajaxcall.AjaxRequest == true;
alert('b');
$.ajax({
type: "POST",
url: ajaxcall.url,
data: ajaxcall.data,
contentType: "application/json; Characterset=utf-8",
dataType: "json",
async: false,
success: function (data) {
if (ajaxcall.callback == true) {
ajaxcall.callbackfunction(data);
}
},
error: function (request, status, error) {
//alert("Exception Handling : \n" + request.responseText);
alert('Unable to process the request at this moment! Please try again later.');
},
complete: function () {
ajaxcall.AjaxRequest = false;
}
});
}
catch (e) {
ajaxcall.AjaxRequest == false;
// alert("Error Catch : " + e.Description + '\n' + 'Message: ' + e.Message);
}
}
},
AjaxFileUpload: function () {
$.ajaxFileUpload({
type: "POST",
url: "../GenericHandlers/FileUploader.ashx?path=" + ajaxcall.folder,
dataType: 'json',
async: false,
secureuri: false,
fileElementClass: ajaxcall.fileElementClass,
success: function (data) {
var data = data.toString();
ajaxcall.filename = data.substring(6, data.length - 7);
alert(ajaxcall.filename);
return true;
}
});
}
};
Now i want to show a div when ajax call starts and hide after finish.
So for that i have used
$(document).ready(function(
$('#Loading').ajaxStart(function () {
alert('a');
$('#Loading').show();
}).ajaxStop(function () {
$('#Loading').hide();
});
});
But when i call the ajax method (defined above in the class), control goes into ajax method first then in ajaxStart.
I don't know why it is happening. Please help.
Use the recommended global for these:
$.ajaxStart(function() {
$("#Loading").show();
});
$.ajaxComplete(function() {
$("#Loading").hide();
});
Try it this way attached to your Loading id element:
$("#Loading").ajaxStart(function() {
$(this).show();
});
$("#Loading").ajaxComplete(function() {
$(this).hide();
});
AjaxStart called when the http request start, not when the ajax method executes.

Resources