Download Base64 image through javascript - javascript

I am working on an image panel that displays the image titles and a link to download the image. I have an onclick function that gathers the base64 data from the database and then 'decodes' it. However, when I decode it I'm getting back a string of Chinese text..which is obviously not what I'm looking for.
$(document).ready(function() {
$('.downloadAttachment').on('click', function() {
var documentId = $(this).attr("data-id");
console.log(documentId)
$.ajax({
dataType: 'json',
//data: id,
async: false,
type: 'GET',
//url: baseUrl + 'rest/incdDocument/getAll?branchCode=' + brCode + '&receivedDate=' + receiveDate + '&complaintID=' + cId + '&incidentID=' + incidentId+ '&documentID='+documentId,
url: baseUrl + 'rest/incdDocument/get?branchCode=009&receivedDate=03/10/2017&complaintID=170&incidentID=3'+'&documentID='+documentId,
success: function(data) {
if (data) {
var image = Base64.decode(data.data);
window.open(image, '_blank');
}
},
error: function(request, status, error) {
console.log(error)
}
});
return false;
})
});
Is there a better way to extract this data and actually turn it into an image?

Searching for like this ?
var image = new Image();
image.src = data; (complete base64 sting with imagetype)
Download Image
Make a download.php file with return the a image with
header('Content-type:image/png'); or other image type

Related

Is there a way to use byte array on html5 source video tag

I am getting a byte array from my mvc action method. I want to set it as source to HTMl video tag. How can it be done. My code is below.
var sourcePDF = '../../Content/Images/video.webm'
if (sourcePDF != undefined && sourcePDF.trim() != "") {
var url = ResolvedUrl.replace('ActionName', 'StreamFile').replace('ControllerName', 'File');
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({ filename: sourcePDF }),
contentType: "application/json; charset=utf-8",
datatype: "JSON",
success: function (response) {
debugger;
console.log(response)
var HealthCareIframeAppend = '<video width="100%" height="inherit" src="' + response + '" autoplay controls ></video>';
$('#HealthCareAttachementi').append(HealthCareIframeAppend);
$('#_SwitchFullScreenContentNewTab').switchClass('show', 'hide');
},
error: function (error) {
console.log(error);
}
});
}
You can use base64 encoded string ant then place it inside your src tad, but it will be bad idea, because it will be huge. You can find demo at here (check source code of this page)
Tutorial how to do that you can find here.
But in your case, additional challenge is how to convert byte array to base64 string, that will consume time and memory, if you still want to do that, you can return base64 string from server
I ended up doing this and it worked fine. It is working perfectly in Chrome and in firefox as well and you can also download the file in Chrome.
Here is my Javascript
var url= '../../Content/Images/video.webm'
var sourceVideo = parent.window.ResolvedUrl.replace('ActionName', 'videoStream').replace('ControllerName', 'File') + '?' + $.param({ "filePath": url });
$('#HealthCareAttachementi video').remove();
$('#HealthCareAttachementi iframe').remove();
var HealthCareIframeAppend = '<video width="100%" height="inherit" autoplay controls > <source src=' + sourceVideo + ' type="video/mp4" ></video>'; $('#HealthCareAttachementi').append(HealthCareIframeAppend);
$('#_SwitchFullScreenContentNewTab').switchClass('show', 'hide');
And here is the Action Method
public void videoStream(string filePath)
{
//The header information
HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=Training.mp4");
var file = new FileInfo(filePath);
//Check the file exist, it will be written into the response
if (file.Exists)
{
var stream = file.OpenRead();
var bytesinfile = new byte[stream.Length];
stream.Read(bytesinfile, 0, (int)file.Length);
HttpContext.Response.BinaryWrite(bytesinfile);
}
}

How to strip a string from unwanted parts?

Given an url like this:
https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,0,295,440_UX32_CR0,0,32,44_AL_.jpg
How do i get it to be like
https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,44_AL_.jpg
The issue I am having is with retrieving IMDB poster images, using this:
$('form[name="search-imdb"]').on("submit", function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
url: "http://imdb.wemakesites.net/api/search",
data: form.serialize(), // assuming the form has a hidden input with api_key name, containing your API key
crossDomain: true,
dataType: "jsonp",
success: function(data) {
window.console.log(data);
}
});
});
I get a json response like:
"thumbnail": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw##._V1_UX32_CR0,0,32,44_AL_.jpg"
I get no poster and the api i am using don't help, yet that thumbnail image is including various formats, one of which is 44_al which is what i would like to leave as a string in order to output it like:
function imdbLoad() {
var form = $("#usp-title").val();
var encodedTerm = encodeURIComponent(form);
$.ajax({
url: "http://imdb.wemakesites.net/api/search",
data: {
q: encodedTerm
},
crossDomain: true,
dataType: "jsonp",
success: function(data) {
$("#imdb").empty();
$.each(data.data.results, function(i, items) {
$("#imdb").append('<h2>'+i+'</h2>');
$.each(items, function(k, item) {
$("#imdb").append("<div class='col-xs-12 col-md-4'><div class='thumbnail'><img class='img-responsive' src='"+ item.thumbnail +"'><div class='caption'><h3>"+ item.title +"</h3><p>"+ item.title +"</p></div></div>");
});
});
}
});
}
Unless anyone has any other way to grab the poster url
You can either use regex to replace string part that is not required
var url = "https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,0,295,440_UX32_CR0,0,32,44_AL_.jpg"
var regex = /,.*(?=,)/g;
console.log(url.replace(regex, ''))
or split using comma(,) and join first and last part.
var url = "https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,0,295,440_UX32_CR0,0,32,44_AL_.jpg"
var parts = url.split(',');
console.log(parts[0] + ',' + parts.pop())
This is a bit of a longer code as I have included few bits such as limiting the number of results but basically what I noticed is that after the ## the whole string is about image size. So instead of using a regex (that would be the answer for this specific question), I could simply add the dimension to the url as a string like:
<img class='img-responsive' src='"+ thumbnailMod[0] + "#._V1_UX500_CR0,0,500,550_AL_.jpg'>
Full code
$('form[name="search-imdb"]').on("submit", function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
url: "http://imdb.wemakesites.net/api/search",
data: {
api_key: "...",
q: form.find('input[name="q"]').val()
},
crossDomain: true,
dataType: "jsonp",
success: function(data) {
$("#imdb").empty();
var thumbnailMod, limiteRes = 1;
if (data.data.results.titles !== undefined) {
$("#imdb").append('<h2>Titles</h2>');
$.each(data.data.results.titles, function(i, item) {
thumbnailMod = item.thumbnail.split('#.');
if (thumbnailMod.length > 1) {
if (limiteRes > 3) {
return;
}
limiteRes++;
$("#imdb").append("<div class='col-xs-12 col-md-4'><div class='thumbnail'><img class='img-responsive' src='"+ thumbnailMod[0] + "#._V1_UX500_CR0,0,500,550_AL_.jpg'><div class='caption'><h3>"+ item.title +"</h3><p>"+ item.title +"</p></div></div>");
}
});
} else {
console.log('No titles found for this search.');
}
}
});
});

Link not opening after streaming data of the document down

I think I am missing some code on the JavaScript side. I am downloading the documents for each request. When the user clicks on the link, I go get the document data and stream it down. I see on Fiddler that the data is coming down, but the .txt document link is not opening.
[HttpGet]
public HttpResponseMessage GetDataFiles(Int64 Id)
{
var results = context.PT_MVC_RequestFile.Where(x => x.RowId == Id).FirstOrDefault();
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
try
{
if (results != null)
{
response.Headers.AcceptRanges.Add("bytes");
response.StatusCode = HttpStatusCode.OK;
response.Content = new ByteArrayContent(results.Data);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = results.FileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentLength = results.Data.Length;
}
}
catch (EntityException ex)
{
throw new EntityException("GetFiles Failed" + ex.Message);
}
return response;
}
Firstly, I downloaded all the documents for that request, and if the user clicks on the file, I call the download stream action.
$.ajax({
url: url,
type: 'GET',
// data: JSON.stringify(model, null),
contentType: "application/json",
success: function (data) {
if (data != "") {
$("#fileLength").val(data.length);
// alert(data.length);
$.each(data, function (i, item) {
var newDiv = $(document.createElement('div')).attr("id", 'file' + i);
newDiv.html("<input id=\"cb" + i + "\" type=\"checkbox\"> <a href=\"#\" onclick=\"GetData('" + item.RowId + "','" + item.mineType + "')\" >" + item.FileName + "</a>");
newDiv.appendTo("#fileRows");
});
} else {
}
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I think I am missing something after success though. Somehow it downloads the data, but the link does not open. Could it be the content type is not set, or that it thinks it is JSON data? Help with some ideas please.
Here is the link:
function GetData(rowId,mineType) {
// alert(mineType);
var url = "api/MyItemsApi/GetDataFiles/" + rowId;
$.ajax({
url: url,
type: 'GET',
//data: JSON.stringify(model, null),
contentType: "application/json",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
You can't easily download a file through an Ajax request. I recommend to post the data to a blank page from a form, instead of the Ajax (you can populate that form and post it via jQuery if you need to). If you're interested, I could guide you through it, just let me know.
If you still want to download from Ajax, I suggest you refer to this post.

When I click button it display image with jQuery ajax on output div 'mouse_move' only for first one but not display same on another click

I am having a problem with image rendering facility on button click display image on output div only for first one but not display same on another click with changes I am doing the code for image meme so that I can write text on image and give some effects. It displays image for the first time only as i told above on click I serialize the form data. after that I passes to ajaxfunctions page by jQuery ajax call.
var data = {
'field_name': 'formdata',
'outer_offset_left': offset.left,
'outer_offset_top': offset.top,
'drag_offset_left': dragOffset.left,
'drag_offset_top': dragOffset.top,
'drag_offset_left2': dragOffset2.left,
'drag_offset_top2': dragOffset2.top,
'outer_width': outerWidth,
'outer_height': outerHeight,
'drag_width': dragWidth,
'drag_height': dragHeight,
'drag_width2': dragWidth2,
'drag_height2': dragHeight2,
'fontsize': font_size,
'fontsize2': font_size2,
'file_name_path': file_path,
'file_background_url': outer_bg_url,
'file_background_color': outer_bg_color,
'drag_text': drag_text,
'drag_text2': drag_text2,
'font_type': font_type,
'font_type2': font_type2,
'shadow_val': shadow_val,
'cap_val': cap_val
};
data = $('#my-form').serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "html",
url: "source/ajax-functions.php",
//Relative or absolute path to response.php file
data: data,
success: function (data) {
setTimeout(function () {
$("#mouse_move").css({
'display': 'block'
}).html(data);
}, 200);
}
});
on ajax-functions.php i have just echo the image after update but it will show output that it generates for the first time.
echo '<img src="'.$pathToImage.'custom_Text_image.jpg" />';
but internally every thing is going fine. image is successfully updated as i want.
This line:
data = $('#my-form').serialize() + "&" + $.param(data);
will add the current form a second time to data on each run. It will only run once properly.
Assumed, data="abc"
// 1
data = $('#my-form').serialize() + "&" + $.param(data);
// <formadata>&abc
// 2
data = $('#my-form').serialize() + "&" + $.param(data);
// <formadata>&abc<formdata>&abc
// etc.
Change:
datatosend = $('#my-form').serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "html",
url: "source/ajax-functions.php",
//Relative or absolute path to response.php file
data: datatosend,
success: function(
...

jQuery: how to get a random number in filename

I'm using the following code to get a html content file from a folder.
$(window).bind('load', function() {
$.ajax({
url: "/folder/htmlcontent1.html",
success: function (data) { $('.attach').append(data); },
dataType: 'html'
});
});
I want to make it random and pick up a random file on every page load. The files will be named incrementally like "htmlcontent1,htmlcontent2". I wonder if it's possible to use Math.floor in the url path like this:
var rand_no = Math.floor((3-1)*Math.random()) + 1;
$.ajax({
url: "/folder/htmlcontent' + rand_no + '.html",
success: function (data) { $('.attach').append(data); },
dataType: 'html'
});
Yes, it's possible. But you must fix the quotes :
url: "/folder/htmlcontent" + rand_no + ".html",

Categories

Resources