Blueimp File Upload: How to delete file? (MVC) - asp.net

I'm attempting to tie Blueimp File Uploader into my MVC 5 solution. I have the uploads working as follows:
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Add files...</span>
<input id="fileupload" type="file" name="files[]" multiple>
</span>
<br />
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
<span class="sr-only">0% complete</span>
</div>
</div>
<br />
<div class="file_name"></div>
<br />
<div class="file_type"></div>
<br />
<div class="file_size"></div>
<!-- The container for the uploaded files -->
<div id="files" class="files"></div>
and the javascript
$(document).ready(function () {
var Url = "#Url.Content("~/Advertise/UploadFiles")";
$('#fileupload').fileupload({
dataType: 'json',
url: Url,
autoUpload: true,
done: function (e, data) {
// $('.file_name').html(data.result.name);
// $('.file_type').html(data.result.type);
// $('.file_size').html(data.result.size);
}
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('#files');
$.each(data.files, function (index, file) {
var node = $('<p/>')
.append('<img src="' + URL.createObjectURL(data.files[0]) + '" height="50" width="50"/>').append($('<span/>').text(file.name));
if (!index) {
node
.append('<br>')
//.append(uploadButton.clone(true).data(data));
}
node.appendTo(data.context);
});
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index,
file = data.files[index],
node = $(data.context.children()[index]);
if (file.preview) {
node
.prepend('<br>')
.prepend(file.preview);
}
if (file.error) {
node
.append('<br>')
.append($('<span class="text-danger"/>').text(file.error));
}
if (index + 1 === data.files.length) {
data.context.find('button')
.text('Upload')
.prop('disabled', !!data.files.error);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
if (file.url) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link);
} else if (file.error) {
var error = $('<span class="text-danger"/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
}
});
}).on('fileuploadfail', function (e, data) {
$.each(data.files, function (index) {
var error = $('<span class="text-danger"/>').text('File upload failed.');
$(data.context.children()[index])
.append('<br>')
.append(error);
});
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
I've not tested a lot of the jQuery above. But I'm looking in to how I can delete an uploaded file? I could probably do it by calling a jQuery ajax post, but I think Blueimp has a native way to do it. But I can't find any documentation on it?? Any help appreciated.

Related

When I type something long with no spaces, it goes off screen

I have some issues with making a chatroom. For some reason whenever I type a long letter or something without spaces, it goes off screen. If I were to add some spaces, it would work.
As you can see here
, the first message has spaces and it worked fine, but the second message had no spaces and it went off the screen, how would I fix this?
server.js
var PORT = process.env.PORT || 3000;
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var moment = require('moment');
var connectedUsers = {};
app.use(express.static(__dirname + '/public'));
io.on('connection', function(socket) {
/*var socketId = socket.id;
var clientIp = socket.request.connection.remoteAddress;
console.log('A user is connected. - IP: ' + clientIp + " | ID: " + socketId);*/
console.log('A user is connected.')
socket.on('disconnect', function() {
var userData = connectedUsers[socket.id];
if (typeof userData !== 'undefined') {
socket.leave(connectedUsers[socket.id]);
io.to(userData.room).emit('message', {
username: 'System',
text: userData.username + ' has left!',
timestamp: moment().valueOf()
});
delete connectedUsers[socket.id];
}
});
socket.on('joinRoom', function(req, callback) {
if (req.room.replace(/\s/g, "").length > 0 && req.username.replace(/\s/g, "").length > 0) {
var nameTaken = false;
Object.keys(connectedUsers).forEach(function(socketId) {
var userInfo = connectedUsers[socketId];
if (userInfo.username.toUpperCase() === req.username.toUpperCase()) {
nameTaken = true;
}
});
if (nameTaken) {
callback({
nameAvailable: false,
error: 'This username is taken, please choose another one.'
});
} else {
connectedUsers[socket.id] = req;
socket.join(req.room);
socket.broadcast.to(req.room).emit('message', {
username: 'System',
text: req.username + ' has joined!',
timestamp: moment().valueOf()
});
callback({
nameAvailable: true
});
}
} else {
callback({
nameAvailable: false,
error: 'Please complete the forum.'
});
}
});
socket.on('message', function(message) {
message.timestamp = moment().valueOf();
io.to(connectedUsers[socket.id].room).emit('message', message);
});
socket.emit('message', {
username: 'System',
text: 'Ask someone to join this chat room to start talking.',
timestamp: moment().valueOf()
});
});
http.listen(PORT, function() {
console.log('Server started on port ' + PORT);
});
index.html body:
<body>
<div class="container">
<div id="login-area">
<div class="row">
<div class="large-7 medium-7 small-12 columns small-centered">
<form id="login-form">
<h2>Twintails🎀 Bot Chatroom</h2>
<p id="error-msg"></p>
<input
type="text"
name="username"
placeholder="Enter your username"
/>
<input
type="text"
name="room"
placeholder="Enter a chat room name"
/>
<input type="submit" value="Join Chat" />
</form>
</div>
</div>
</div>
<div class="row" id="message-area">
<div class="large-8 columns small-centered">
<h2>Twintails🎀 Bot Chatroom</h2>
<div class="chat-wrap">
<div class="top">
<h5 class="room-title"></h5>
</div>
<div id="messages"></div>
<form id="message-form">
<div class="input-group">
<input
type="text"
placeholder="Type message here"
class="input-group-field"
name="message"
/>
<div class="input-group-button">
<input type="submit" value="Send" />
</div>
</div>
</form>
</div>
</div>
</div>
<footer>
<p>
Add the
<a href="https://twintails-bot-dashboard.glitch.me/" target="_blank"
>Twintails🎀 bot!</a
>
</p>
<p>
Use the 'Mod' room to talk to mods!
</p>
</footer>
</div>
<script src="/js/jquery.js"></script>
<script src="/js/socket.io-1.7.3.min.js"></script>
<script src="/js/moment.min.js"></script>
<script src="/js/app.js"></script>
<script src="/js/foundation.min.js"></script>
<script type="text/javascript">
$(document).foundation();
</script>
</body>
If you need some info on the css, just comment and I'll edit this post.

Resetting VueJS Pagination on watch change

I am working on a small VueJS app that pulls in WordPress posts via the API. Everything works great with pagination to load more posts, however I am not too sure how I can reset the entire XHR getPosts method when you change the user ID radio field.
When you change the author ID currently, it will not reset the results. I believe it should be something in the watch: area to destroy the current page - but not too sure. Thanks!
https://codepen.io/sco/pen/aRwwGd
JS
Vue.component("posts", {
template: `
<ul>
<slot></slot>
</ul>
`
});
Vue.component("post", {
props: ["title", "excerpt", "permalink"],
template: `
<li>
<h3 v-html="title"></h3>
<div v-if="excerpt" v-html="excerpt"></div>
<a :href="permalink">Read More</a>
</li>
`
});
var App = new Vue({
el: "#app",
data: {
greeting: "Load more Posts Vue + WP REST API",
page: 0,
posts: [],
totalPages: "",
apiURL: "https://poststatus.com/wp-json/wp/v2/posts/?per_page=2",
isLoading: "",
show: true,
authors: [1, 590],
currentAuthor: ""
},
watch: {
currentAuthor: "fetchData"
},
methods: {
getPosts: function() {
var xhr = new XMLHttpRequest();
var self = this;
self.page++;
self.isLoading = "is-loading";
xhr.open(
"GET",
self.apiURL + "&page=" + self.page + "&author=" + self.currentAuthor
);
xhr.onload = function() {
self.totalPages = xhr.getResponseHeader("X-WP-TotalPages");
if (self.page == self.totalPages) {
self.show = false;
}
var newPosts = JSON.parse(xhr.responseText);
newPosts.forEach(function(element) {
self.posts.push(element);
});
self.isLoading = null;
//console.log(self.apiURL + self.page)
};
xhr.send();
}
}
});
HTML
<section id="app" class="wrapper">
<div class="container">
<div class="box">
<template v-for="author in authors">
<div class="author-toggle">
<input type="radio"
:id="author"
:value="author"
name="author"
v-model="currentAuthor">
<label :for="author">{{ author }}</label>
</div>
</template><br>
<h3 v-if="page>0">Showing Page {{page}} of {{totalPages}}</h3>
<progress v-if="page>0" class="progress" :value="page" :max="totalPages">{{page}}</progress>
<posts v-if="posts">
<post v-for="post in posts" class="post" :id="'post' + post.id" :title="post.title.rendered" :permalink="post.link" :key="post.id">
</post>
</posts>
<button :class="isLoading + ' ' +'button is-primary'" v-if="show" #click="getPosts(page)">Load Posts</button>
</div>
</div>
</section>
You can reset page, posts, and totalPages inside the watcher:
watch: {
currentAuthor() {
this.page = 0;
this.totalPages = 0;
this.posts = [];
this.getPosts();
}
}
your codepen with required changes

Two recaptcha controls, one of them is not working

I have two reCaptcha V2 controls within two forms in one page, one is visible another is invisible. All is fine except the invisible one's data-callback callback - submitSendForm() did not get called. Once I removed the visible one, the invisible one starts working.
So the process is like once user completed the first visible challenge then the second form(within same page) will show with the invisible one, that's when the call back failed to be called.
It hasn't to be one visible and another invisible. But I found this to be easy when you want to have multiple controls.
Here is the code:
using (Html.BeginForm("Verify", "CertificateValidation", FormMethod.Post, new { id = "verifyForm" }))
{
<div class="form-group">
<div class="g-recaptcha" data-sitekey='site-key' data-callback="enableBtn"
style="transform: scale(0.66); transform-origin: 0 0;">
</div>
<div class="col-sm-3">
<button type="submit" id="verify" disabled>Verify</button>
</div>
</div>
}
using (Html.BeginForm("Send", "CertificateValidation", FormMethod.Post, new { id = "sendForm" }))
{
<div id='recaptcha1' class="g-recaptcha"
data-sitekey='site-key'
data-callback="submitSendForm"
data-size="invisible"></div>
<button type="submit">Send</button>
}
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script type="text/javascript">
function submitSendForm() {
console.log('captcha completed.');
$('#sendForm').submit();
}
$('#sendForm').submit(function (event) {
console.log('form submitted.');
if (!grecaptcha.getResponse()) {
console.log('captcha not yet completed.');
event.preventDefault(); //prevent form submit
grecaptcha.execute();
} else {
console.log('form really submitted.');
}
});
var enableBtn = function (g_recaptcha_response) {
$('#verify').prop('disabled', false);
};
$(document).ready(function () {
$('#verify').click(function () {
$captcha = $('#recaptcha');
response = grecaptcha.getResponse();
if (response.length === 0) {
return false;
} else {
return true;
}
});
});
</script>
I got it figured out somehow:
var CaptchaCallback = function () {
grecaptcha.render('RecaptchaField1', { 'sitekey': 'site-key', 'callback': 'enableBtn' });
window.recaptchaField2Id = grecaptcha.render('RecaptchaField2', { 'sitekey': 'site-key', 'callback': 'submitSendForm', 'size': 'invisible' });
};
function submitSendForm() {
$('#sendForm').submit();
}
$('#sendForm').submit(function (event) {
if (!grecaptcha.getResponse(window.recaptchaField2Id)) {
event.preventDefault();
grecaptcha.execute(window.recaptchaField2Id);
}
});
using (Html.BeginForm("Verify", "CertificateValidation", FormMethod.Post, new { id = "verifyForm" }))
{
<div class="form-group">
<div style="transform: scale(0.66); transform-origin: 0 0;" id="RecaptchaField1"></div>
<div class="col-sm-3">
<button type="submit" id="verify" disabled>Verify</button>
</div>
</div>
}
using (Html.BeginForm("Send", "CertificateValidation", FormMethod.Post, new { id = "sendForm" }))
{
<div id="RecaptchaField2"></div>
<button type="submit">Send</button>
}
This one worked for me, clean and easy.
Javascript
var reCaptcha1;
var reCaptcha2;
function LoadCaptcha() {
reCaptcha1 = grecaptcha.render('Element_ID1', {
'sitekey': 'your_site_key'
});
reCaptcha2 = grecaptcha.render('Element_ID2', {
'sitekey': 'your_site_key'
});
};
function CheckCaptcha1() {
var response = grecaptcha.getResponse(reCaptcha1);
if (response.length == 0) {
return false; //visitor didn't do the check
};
};
function CheckCaptcha2() {
var response = grecaptcha.getResponse(reCaptcha2);
if (response.length == 0) {
return false; //visitor didn't do the check
};
};
HTML
<head>
<script src="https://www.google.com/recaptcha/api.js?onload=LoadCaptcha&render=explicit" async defer></script>
</head>
<body>
<div id="Element_ID1"></div>
<div id="Element_ID1"></div>
</body>

Image Upload not working in Meteor

In my meteor app I am uploading images and storing them in dropbox. It works fine when I am running the app in localhost. But as soon as I run the app after deploying it to meteor.com the upload fails to work.
This is my code in server.js
var createThumb = function(fileObj, readStream, writeStream) {
// Transform the image into a 10x10px thumbnail
gm(readStream, fileObj.name()).resize('10', '10').stream().pipe(writeStream);
};
var dropboxStore = new FS.Store.Dropbox("files", {
key: "",
secret: "",
token: "", // Don’t share your access token with anyone.
transformWrite: createThumb, //optional
})
Images = new FS.Collection("files", {
stores: [dropboxStore]
});
Images.allow({
'insert': function () {
// add custom authentication code here
return true;
}
});
Here is the link to meteor.com http://image_upload.meteor.com/.
I have tried changing dropbox to s3 but it still doesn't work. Could it be because it is hosted at meteor.com?
Looking forward for a solution.
Most likely it's because you're trying to use GraphicsMagick to resize the image in the transformWrite option, but meteor.com hosting servers do not have GraphicsMagick or ImageMagick installed.
https://github.com/CollectionFS/Meteor-CollectionFS/issues/299
You can use the meteor logs command to view the logs from your hosted meteor.com application to make sure that's the issue.
Edit
Here's some sample code for the jQuery cropper utility:
Template HTML:
<input type="file" style="visibility:hidden;width:1px" accept="image/gif, image/jpeg, image/png" class="profilePhotoFile">
<input type="button" id="btnEditPhoto" value="Edit Photo" class="btn btn-primary" style="width:160px"/>
<div class="modal fade" id="cropper-modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<div id="cropper">
<img src="" alt="Picture">
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" id="btnSavePhoto">Save</button>
<button class="btn btn-default" id="btnCancel">Cancel</button>
</div>
</div>
</div>
</div>
Template JS:
Template.myTemplate.events({
'click #btnEditPhoto': function(event, template) {
$('.profilePhotoFile').click();
},
'change .profilePhotoFile': function(event, template) {
if (!event.target.files || event.target.files.length === 0) {
return;
} else {
var $inputImage = $(event.target);
var URL = window.URL || window.webkitURL;
var file = event.target.files[0];
var blobURL = URL.createObjectURL(file);
$image = $('#cropper > img');
$('#cropper-modal').modal();
$('#cropper-modal').on('shown.bs.modal', function() {
$image.cropper({
aspectRatio: 1.0,
autoCropArea: 1.0
}).cropper('replace', blobURL);
$inputImage.val('');
}).on('hidden.bs.modal', function() {
$image.cropper('destroy');
URL.revokeObjectURL(blobURL); // Revoke url
});
}
},
'click #btnSavePhoto': function(event, template) {
$image = $('#cropper > img');
//Change the width and height to your desired size
var base64EncodedImage = $image.cropper('getCroppedCanvas', {width: 10, height: 10}).toDataURL('image/jpeg');
$('#cropper-modal').modal('hide');
var newImage = new FS.File(base64EncodedImage);
Images.insert(newImage, function(err, fileObj) {
if (err) {
console.log(err);
} else {
//do something after insert
}
});
},
'click #btnCancel': function(event, template) {
$('#cropper-modal').modal('hide');
}
});

File upload not working with angular and webmethod

I am basically trying to upload a file using angular and a webmethod.
I took the code from this blog but it does not work. The request is successfull as seen from fiddler but the web method never gets invoked.
Am I doing something wrong?
Following is my code .
angular
.module('loader', ['ui.router', 'ui.bootstrap', 'ui.filters'])
.controller('loader-main', function($rootScope, $scope, WebServices) {
$scope.uploadNewFile = function() {
WebServices.uploadFile($scope.myfile);
}
}).factory('WebServices', function($rootScope, $http) {
return {
postFile: function(method, uploadData) {
var uploadUrl = "myASPXPAGE.aspx/" + method;
return $http.post(uploadUrl, uploadData, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
}).success(function(data) {
///Control reaches here but never hits the server method
});
},
uploadFile: function(filedata) {
var fd = new FormData();
fd.append('file', filedata);
return this.postFile("UploadFile", fd);
}
};
}).directive('fileModel', ['$parse',
function($parse) {
return {
restrict: 'A',
link: function($scope, element, attr) {
var model = $parse(attr.fileModel);
var modelSetter = model.assign;
element.bind('change', function() {
$scope.$apply(function() {
modelSetter($scope, element[0].files[0]);
});
});
}
}
}
]);
<div class="row">
<div class="col-xs-5">
<div class="col-xs-4">Browse to File:</div>
<div class="col-xs-1">
<input type="file" id="uploadFile" class="btn btn-default" file-model="myfile" />
<input type="button" class="btn btn-primary" value="Load File" data-ng-click="uploadNewFile()" />
</div>
</div>
</div>
And here is my WebMethod
[WebMethod]
public static string UploadFile()
{
System.Diagnostics.Debugger.Break();
return "Done";
}
Figured it out. You cannot have Content-Type as multipart/form-data in webmethods. Instead created a HttpHandler to upload the file and everything works just fine.

Resources