gravity form preview thumbnails for multi file upload field - wordpress

We are using Gravity Forms to attach multiple images to a gallery custom field and create new post. We can't figure out how to show the image thumbnails under the import HTML5 import field instead of just the file names prior to form submission.
This previous answer covers only single file upload: gravity form preview of image upload
That mechanism is different it seems.
I also see GF offers a JS function to filter the image data returned but I can't figure out how to get the temporary img urls to display tags. That reference is here:
gform.addFilter('gform_file_upload_markup', function (html, file, up, strings, imagesUrl) {
var formId = up.settings.multipart_params.form_id,
fieldId = up.settings.multipart_params.field_id;
html = '<strong>' + file.name + "</strong> <img class='gform_delete' "
+ "src='" + imagesUrl + "/delete.png' "
+ "onclick='gformDeleteUploadedFile(" + formId + "," + fieldId + ", this);' "
+ "alt='" + strings.delete_file + "' title='" + strings.delete_file + "' />";
return html;
});

To show the preview of the image with just thumbnail size. You need to convert your image to the base64 so it will not take much time to load and it will show perfect.
/**
* Upload image action for Gravity Forms
* This script displays the thumbnail upon image upload for multi file field.
*
*/
function gravity_image_thumb() {
if ( is_page('slugname') ) {
?>
<script type="text/javascript">
gform.addFilter('gform_file_upload_markup', function (html, file, up, strings, imagesUrl) {
//alert(strings);
//Path of your temp file
var myFilePath = '/wp-content/uploads/gravity_forms/FormNameFolderURL/tmp/';
var formId = up.settings.multipart_params.form_id,
fieldId = up.settings.multipart_params.field_id;
var fileName = up.settings.multipart_params.gform_unique_id + '_input_' + fieldId +'_'+ file.target_name;
var fid = "fid"+ Math.ceil((Math.random() * (10000 - 1000)) + 1000);
//Converting Image to the base64
function convertImgToBase64URL(url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'), dataURL;
canvas.height = (300 * img.height)/img.width;
canvas.width = 300; //img.width;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
convertImgToBase64URL(myFilePath + fileName , function(base64Img){
var ffid = "#"+fid;
$(ffid).attr("src", base64Img);
console.log('RESULT:', base64Img);
});
html = '<img id="'+fid+"\" src='' style='width:100%;height:auto;'/><img class='gform_delete' " + "src='" + imagesUrl + "/delete.png' "+ "onclick='gformDeleteUploadedFile(" + formId + "," + fieldId + ", this);' " + "alt='" + strings.delete_file + "' title='" + strings.delete_file + "' />";
return html;
});
</script>
<?php }
}
add_action('wp_head','gravity_image_thumb');

Have you found a Solution for this?
If not, I would like to share mine:
gform.addFilter('gform_file_upload_markup', function (html, file, up, strings, imagesUrl) {
var myFilePath = 'https://your-domain.com/wp-content/uploads/gravity_forms/1-0bfa8914c61ec9b6ff8b3e2c78f497f4/tmp/';
var formId = up.settings.multipart_params.form_id,
fieldId = up.settings.multipart_params.field_id;
var fileName = up.settings.multipart_params.gform_unique_id + '_input_' + fieldId +'_'+ file.target_name;
html = '<img src="' + myFilePath + fileName + "\"/>' <img class='gform_delete' "
+ "src='" + imagesUrl + "/delete.png' "
+ "onclick='gformDeleteUploadedFile(" + formId + "," + fieldId + ", this);' "
+ "alt='" + strings.delete_file + "' title='" + strings.delete_file + "' />";
return html;
});
I am using the image in /tmp, because that's the folder where the Image gets uploaded before the Form is submitted completley.
/{some-numbers-and-letters}/
this is the Folder where the tmp Folder is located. I guess you can change that.

Related

How to add file attachment to Email message sent from Razor page (with ASP.NET Core and MailKit)

The following is a method for sending an Email from a Razor page in ASP.NET Core. I need to use MailKit since System.Net.Mail is not available in ASP.NET Core.
Despite much research, I haven't been able to figure out a way to include the image to the Email. Note that it doesn't have to be an attachment - embedding the image will work.
public ActionResult Contribute([Bind("SubmitterScope, SubmitterLocation, SubmitterItem, SubmitterCategory, SubmitterEmail, SubmitterAcceptsTerms, SubmitterPicture")]
EmailFormModel model)
{
if (ModelState.IsValid)
{
try
{
var emailName= _appSettings.EmailName;
var emailAddress = _appSettings.EmailAddress;
var emailPassword = _appSettings.EmailPassword;
var message = new MimeMessage();
message.From.Add(new MailboxAddress(emailName, emailAddress));
message.To.Add(new MailboxAddress(emailName, emailAddress));
message.Subject = "Record Submission From: " + model.SubmitterEmail.ToString();
message.Body = new TextPart("plain")
{
Text = "Scope: " + model.SubmitterScope.ToString() + "\n" +
"Zip Code: " + model.SubmitterLocation.ToString() + "\n" +
"Item Description: " + model.SubmitterItem.ToString() + "\n" +
"Category: " + model.SubmitterCategory + "\n" +
"Submitted By: " + model.SubmitterEmail + "\n" +
// This is the file that should be attached.
//"Picture: " + model.SubmitterPicture + "\n" +
"Terms Accepted: " + model.SubmitterAcceptsTerms + "\n"
};
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
client.Authenticate(emailAddress, emailPassword);
client.Send(message);
client.Disconnect(true);
return RedirectToAction("Success");
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message + ": " + ex.StackTrace);
return RedirectToAction("Failure");
}
}
else
{
return View();
}
}
This is from the FAQ on Mailkit github repo, and seems to cover the full process.
https://github.com/jstedfast/MailKit/blob/master/FAQ.md#CreateAttachments
var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey", "joey#friends.com"));
message.To.Add (new MailboxAddress ("Alice", "alice#wonderland.com"));
message.Subject = "How you doin?";
// create our message text, just like before (except don't set it as the message.Body)
var body = new TextPart ("plain") {
Text = #"Hey Alice,
What are you up to this weekend? Monica is throwing one of her parties on
Saturday and I was hoping you could make it.
Will you be my +1?
-- Joey
"
};
// create an image attachment for the file located at path
var attachment = new MimePart ("image", "gif") {
ContentObject = new ContentObject (File.OpenRead (path), ContentEncoding.Default),
ContentDisposition = new ContentDisposition (ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
FileName = Path.GetFileName (path)
};
// now create the multipart/mixed container to hold the message text and the
// image attachment
var multipart = new Multipart ("mixed");
multipart.Add (body);
multipart.Add (attachment);
// now set the multipart/mixed as the message body
message.Body = multipart;

Can't move file , because is used by another process

I have many files in one directory, My app, must move some files to another directory. When I did this, first time works fine, but after that I have a exception like:
System.IO.IOException: process cannot access the file because another process is using the file.
I close windows explorer, or any program, avoiding the use of the file, but the problem persists.
I move files in this way:
private void ExtractosRemover()
{
string dirOrigen = '\\' + #"\" + servidor + #"\" + "EEQ_" + User.Identity.Name.ToString() + #"\";
string dirDestin = '\\' + #"\" + servidor + #"\" + "FacturasMatch_" + User.Identity.Name.ToString() + #"\";
try
{
foreach (GridViewRow grd_Row in this.gvwExtractosMatch.Rows)
{
File.Move(System.IO.Path.Combine(dirOrigen, clean(grd_Row.Cells[7].Text) + ".xml"), dirDestin);
}
}
catch (FileNotFoundException)
{
}
catch (IOException ioex)
{
lbl_UbiDevMensaje.Text = string.Empty;
lbl_UbiDevMensaje.Text = ioex.ToString();
}
}
For the names of the files, I read a gridview, and I add the extensions.
I don't know what is happening,
Please, I hope somebody can help me.
Thanks in advance.
best regards
Solved,
Using server map
private void ExtractosRemover()
{
string dirOrigen = "~/" + "EEQ_" + User.Identity.Name.ToString() + "/";
string dirDestin = "~/" + "FacturasMatch_" + User.Identity.Name.ToString() + "/";
foreach (GridViewRow grd_Row in this.gvwExtractosMatch.Rows)
{
try
{
File.Move( //Mover xml
Server.MapPath(dirOrigen + clean(grd_Row.Cells[7].Text) + ".xml"),
Server.MapPath(dirDestin + clean(grd_Row.Cells[7].Text) + ".xml")
);
File.Move( //Mover pdf
Server.MapPath(dirOrigen + "RIDE_" + clean(grd_Row.Cells[7].Text) + ".pdf"),
Server.MapPath(dirDestin + "RIDE_" + clean(grd_Row.Cells[7].Text) + ".pdf")
);
}
catch (FileNotFoundException)
{ }
}
}

MeteorJS allow injection of anchor tag

I have a basic chat that reads from a database. Each chat message is read from the database by this.
<span>{{formatChat text}}</span>
text being the message read.
And then I use the formatChat registerHelper to detect URLs.
Template.registerHelper('formatChat', function(text) {
var urlRegex = /https?:\/\/([a-zA-Z0-9\-\.]+)(\.[a-zA-Z0-9]+)((([a-zA-Z0-9\?\=\/])+)?((\#|\?)(.+)?)?)?$/
var urlRegexMini = /(www(\d{0,3})\.)?([a-zA-Z0-9\-\.]+)(\.(com|net|org|gov|co\.uk|edu|io\b)+)([a-zA-Z0-9\?\=\/]+((([a-zA-Z0-9\?\=\/])+)?((\#|\?)(.+)?)?)?)?$/
finalString = "";
//Parse every word individually
split = text.split(' ');
for (i = 0; i < split.length; i++) {
finalString += " ";
if (urlRegex.test(split[i])) {
finalString += "<a href='" + split[i] + "'>" + split[i] + "</a>";
}
else if (urlRegexMini.test(split[i])) {
finalString += "<a href='http://" + split[i] + "'>" + split[i] + "</a>";
}else{
finalString += split[i];
}
}
return finalString.substring(1,finalString.length);
});
The problem is that meteor doesn't allow injection, so it will literally show the anchor tag as plain text.
One solution that I thought of was to have a registerHelper for each individual word, but that seems rather foolish.
How can I efficiently get around this rule?
I believe this should do it:
{{{formatChat text}}}

html onclick not working when passing in function

I know there are some posts on this, but none have quite fit what I'm looking for exactly.
I'm creating a simple version of twitter. My goal here exactly is to click on a user's handle (user link) and then display all their tweets. I'm using html's onclick and passing in a function, but this gets displayed: #[object Object],[object Object]: [object Object],[object Object] [object Object],[object Object]
The tweets all get wiped out, but now no tweets display. looks like in the js console i'm getting the right objects (person's tweets), but they just aren't displaying on the page properly. do you know what needs to happen here? any help in the right direction would be awesome.
Here's my relevant code:
var tweetCount;
var newCount;
var initialTweets = function() {
tweetCount = streams.home.length;
for(var i = 0; i < tweetCount; i++) {
var tweet = streams.home[i];
displayTweet(tweet);
}
};
var extraTweets = function() {
newCount = streams.home.length;
for(var i = tweetCount; i < newCount; i++) {
var tweet = streams.home[i];
displayTweet(tweet);
}
tweetCount = newCount;
};
var displayTweet = function(tweet) {
var $tweet = $('<div></div>');
var userLink = "<a href='#' onclick='displayUserTweets("+ tweet.user +")'>" + tweet.user + "</a>";
$tweet.html('#' + userLink + ': ' + tweet.message + ' ' + tweet.created_at);
$('#tweetContainer').prepend($tweet);
};
var displayUserTweets = function(user) {
$('#tweetContainer').html('<div></div>');
var $userTweets = $('<div></div>');
var userTweets = streams.users[user];
$userTweets.html('#' + userTweets.user + ': ' + userTweets.message + ' ' + userTweets.created_at);
$('#tweetContainer').prepend($userTweets);
};
initialTweets();
$(document).ready(function(){
$('button').on('click', function() {
extraTweets()
});
});
You are passing user as a onclick handler here, which should be javascript function.
var userLink = "<a href='#' onclick='"+ tweet.user +"'>" + tweet.user + "</a>";
"tweet.user" it should be javascript function name like below:
function showUserTweets(username) {
// write you logic here to get the user tweets by using his username;
}
hence you code will look like something below:
var userLink = "<a href='#' onclick='showUserTweets(\""+ tweet.user +"\")'>" + tweet.user + "</a>";
Note: You tweet.user must return String value. For object you have convert your object into JSON string by using JSON.strigify(object) method.
Hope it helps you!
As i found that you passing a variable to the onclick. which is not a valid method. such that tweet.user is not a valid method.
var displayTweet = function(tweet) {
var $tweet = $('<div></div>');
var userLink = "<a href='#' onclick='"+ tweet.user +"'>" + tweet.user + "</a>";
$tweet.html('#' + userLink + ': ' + tweet.message + ' ' + tweet.created_at);
$('#tweetContainer').prepend($tweet);
};
Here i am writing to solution:
Firstly create a function
function yourFunction(){
// do your stuff
}
Then you can call using one of the following replace your line :
var userLink = "<a href='#' onclick='"+ tweet.user +"'>" + tweet.user + "</a>";
to this
var userLink = "<a href='javascript:void(0);' onclick='yourFunction('+"'"+ tweet.user +"'"+")'>" + tweet.user + "</a>";
OR
var userLink = "<a href='javascript:yourFunction('+"'"+tweet.user+"'"+');'
and remove your these function

how can i access facebook full size album photos using asp.net

i want to show full size or any size facebook photo on my page using asp.net
but i am not able to do this by type in url.
here is my code.
public FacebookAlbums GetFacebookAlbums(string userName, string accessToken)
{
string url = "https://graph.facebook.com/" + userName + "/albums?access_token=" + accessToken;
return Tools.CallUrl<FacebookAlbums>(url);
}
public FacebookPhotos GetPhotosOfAlbum(string albumId, string accessToken)
{
string url = "https://graph.facebook.com/" + albumId + "/photos?type=large&access_token=" + accessToken;
return Tools.CallUrl<FacebookPhotos>(url);
}
this is how i am accessing the above class.
public void GetFacebookAlbums()
{
FacebookDetails FBDetail = new FacebookRepository().GetFacebookDetail();
FacebookAlbums FBAlbums = new FacebookRepository().GetFacebookAlbums(FBDetail.FacebookId, FBDetail.FacebookAccessToken);
StringBuilder sbHtml = new StringBuilder();
FBAlbums.data.ForEach(_albums =>
{
sbHtml.Append("<h3>" + _albums.name + "</h3><ul>");
FacebookPhotos fbPhotos = new FacebookRepository().GetPhotosOfAlbum(_albums.id, FBDetail.FacebookAccessToken);
fbPhotos.data.ForEach(_photo =>
{
sbHtml.Append("<li><img src=\"" + _photo.picture + "\" /></li>");
});
sbHtml.Append("</ul> <br>");
});
ltDisplayPhotos.Text = sbHtml.ToString();
}
here i am making the connection with facebook like
string strFBUrl = "https://graph.facebook.com/oauth/authorize?client_id=" + FacebookRepository.FacebookAppID + "&" +
"redirect_uri=http://" + strHostAddress + #"/FBAuthorise.aspx&scope=user_photos,user_videos,publish_stream,offline_access,user_photo_video_tags";

Resources