How to download and rename jpg image with angularjs - html

Can't download and rename a jpg image.Instead it downloads a corrupted jpg file, that if you change the extension to ".txt" you can see the path of the image in there.
The original code that I had working was the following:
function downloadImg(id){
var deferred = $q.defer();
$http({
method: 'GET',
url: API_URL + 'image/' + id
}).then(function(res){
console.log(res.data);
if(res.data && res.data.length > 0){
window.location.href = res.data;
}
deferred.resolve();
}, function(err){
console.log(err);
deferred.reject();
})
return deferred.promise;
}
So, I just want to rename the image before or after download it.
I end up with this code, that the only thing that is doing is setting the image path into a file or in this case [object Object] in the file(depending on the code I'm using I endup with object... or the image path...).
function downloadImg(id){
var deferred = $q.defer();
$http({
method: 'GET',
url: API_URL + 'image/' + id,
responseType: 'blob'
}).then(function(res){
console.log(res.data);
var file = new Blob([res], {type: 'image/jpeg;charset=UTF-8'});
var fileURL = URL.createObjectURL(file);
var a = document.createElement("a");
a.href = fileURL;
a.download = "newName.jpg";
a.click();
deferred.resolve();
}, function(err){
console.log(err);
deferred.reject();
})
return deferred.promise;
}
Also I tried setting responseType:'arraybuffer'and blob as well as tried to using FileSaver.saveAsand tried to create a blob from base64 found at : http://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript
My image url is something like (I replace some things with "personalName" because I can't share the image): https://personalName.personalName.com/component/get?id=cbd6a354-1700-11e8-b451-0a540af4044a&username=personalName&apiKey=a393ceba-1350-11e6-9382-f23c91df2143
I expected to have the original jpg image, but with the new name.
Thanks.

Related

Code in source panel of developers tools is different from actual file of same file. It is not getting updated

The actual file contain this code
<script>
$(document).ready(function(event){
let affPercent;
let val;
const size = '<?php echo $size;?>';
for(let i = 1; i<=size;i++) {
$(`#affiliate-percentage-${i}`).on('input',function(){
affPercent = $(`#affiliate-percentage-${i}`).val();
console.log(affPercent+" input $");
});
$(`#button-${i}`).click(function(event){
event.preventDefault();
val = $(`#button-${i}`).val();
console.log(affPercent+" click-btn "+val);
$.ajax({
type: 'post',
url: 'index.php',
data: 'sno=' + val + '&affPercent=' + affPercent,
success:function(result){
location.reload(true);
}
});
});
}
});
</script>
But, code in source tab apppears like this
<script>
const getValue =>{
let = document.getElementById("myInput").value;
}
$(document).ready(function (){
const size = '3';
for(let i = 1; i<=size;i++) {
$(`#button-${i}`).click(function(event){
event.preventDefault();
let val = $(`#button-${i}`).val();
let affPercent = $(`#affiliate-percentage-${i}`).val();
$.ajax({
type: 'post',
url: 'index.php',
data: 'sno=' + val + '&affPercent=' + affPercent,
success:function(result){
location.reload(true);
}
});
} );
}
});
</script>
As I changed the file content yesterday, but it is not changed till now in developers tool.
Please help.
This is part of my final year project and no more day left to this.
I am very grateful to you all if you fix my issue.
Thank you

How to integrate tinymce for local image uploading at codeigniter

<script>
tinymce.init({
selector: 'textarea',
plugins: 'image code',
toolbar: 'undo redo | image code',
// without images_upload_url set, Upload tab won't show up
images_upload_url: '<?= base_url("upload.php"); ?>',
// override default upload handler to simulate successful upload
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', '<?= base_url("upload.php"); ?>');
xhr.onload = function() {
var json;
if (xhr.status != 200) {
failure('HTTP Error: ' + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != 'string') {
failure('Invalid JSON: ' + xhr.responseText);
return;
}
success(json.location);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
},
});
</script>
// this code does not work
Every file-manager need to any text editor like ckeditor you must use an editor this file-manager has a documentation and installation you must read it in the main site.
you can see documentation in this URL https://www.tinymce.com/docs/

Download csv format using Angularjs

Node service: shown below are node service call where getting data from mysql query. And converting to json2csv format.
function getData(req,res){
var json2csv = require('json2csv');
var resultset = {};
resultset.data = [];
var nodeExcel=require('excel-export');
var dateFormat = require('dateformat');
var queryString = "select name ,class ,fname from details"
connection.query(queryString, function(err, result) {
if(err) {
console.log('error ',err);
resultset.success=false;
res.writeHead(200, {
'Content-Type': 'application/json'
});
var resultData =resultset;
res.write(JSON.stringify(resultData));
res.end();
} else {
if(result.length>0) {
for(var i=0;i<result.length;i++) {
resultset.data[i]={};
var arr=_(result[i]).toArray();
resultset.data[i].name=arr[0]!=null?arr[0]:null;
resultset.data[i].class=arr[1]!=null?arr[1]:null;
resultset.data[i].fname=arr[2]!=null?arr[2]:null;
}
resultset.success=true;
res.writeHead(200, {
'Content-Type': 'application/json'
});
var resultData =json2csv(resultset);
console.log("resultData",resultData);
res.write(JSON.stringify(resultData));
res.end();
}
else{
resultset.success = false;
res.writeHead(200, {
'Content-Type': 'application/json'
});
var resultData = resultset;
res.write(JSON.stringify(resultData));
res.end();
}
}
});
}
Controller:
getting the service response.
$scope.Details=function(data,fileName){
$http.get(Data.baseNodeService+'getData',headconfig).then(function(response,fileName){
$scope.det = response.data.data;
var element = angular.element('');
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI($scope.det),
target: '_blank',
download: 'filename.csv'
})[0].click();
});
}
On click Html Download:
<input type="button" class="bt-submit" ng-click="Details()" value="Download" />
But I am getting download output as [object Object].I want to get data from my service call and download in csv format.
You can download CSV in different ways, this below is a common way to download file
var a = document.createElement('a');
a.href = 'data:'+mimeType+';charset=utf-8;base64,' + response;
a.target = '_blank';
a.download = "name the file here";
document.body.appendChild(a);
a.click();
use the mimeType as your file type here for csv it would be attachment/csv but this won;t work on safari.
There is awseome library https://github.com/alferov/angular-file-saver You can use this.
You can call it like
function download(api, file, contentType) {
var d = $q.defer();
$http({
method: 'GET',
url: api,
responseType: 'arraybuffer',
headers: {
'Content-type': contentType
}
}).success(function(response) {
var data = new Blob([response], {
type: contentType+ ';charset=utf-8'
});
FileSaver.saveAs(data, file);
d.resolve(response);
}).error(function(response) {
d.reject(response);
});
return d.promise;
}
Also see my other answers on file download
how to export data into CSV and PDF files using angularjs
And
AngularJS - Receive and download CSV
Try this:-
/*this section for CSV*/
if(window.navigator.msSaveOrOpenBlob && window.Blob) {
var blob = new Blob([response.data.data], {type: "text/csv"});
navigator.msSaveOrOpenBlob(blob, new Date().getTime() + '.csv');
} else {
var anchor = angular.element('<a/>').css({display: 'none'});
angular.element(document.body).append(anchor); // Attach to document
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(response.data.data),
target: '_blank',
download: new Date().getTime() + '.csv'
})[0].click();
anchor.remove();
}

Failed to load resource: net::ERR_CONNECTION_REFUSED, when i post the request. I'm using angular JS, node JS and gulp to insert to my JSON

.controller("addContact",function($scope,$http){
$scope.add=function(){
var myContact={
"department":$scope.department,
"name":$scope.name,
"model":$scope.model,
"year":$scope.year,
"price":$scope.price
};
console.log(myContact);
$http.post("/addItem",myContact)
.then(function(response){
console.log(response);
});
public.post('/addItem',function(request,response){
console.log("incoming data=" +request.body);
fs.readFile(__dirname + "/public/items.json", 'utf-8', function(err, data) {
console.log('file data' + data);
var fileJsonData = data;
var newContact = request.body;
newContact.id = fileJsonData.items.length + 1;
console.log("newContact=" + JSON.stringify(newContact));
fileJsonData.items.push(newContact);
var stringFile = JSON.stringify(fileJsonData);
fs.writeFile(__dirname + "/items.json", stringFile);
response.send(stringFile);
});
});
Please check if any of your interceptors are causing this issue. Also check the status of the response to check if it makes sense.
This post might help you Angular.js $http intercept "net::ERR_CONNECTION_REFUSED"
Take some time to read the document for $http.post as I think you are not using it the correct way

How to put png binary data into an img tag and display it as an image?

I am using this
$.ajax({
type: "GET",
url: 'template/bump1/purse.png',
datatype:"image/png",
success: function (data) {
var reader = new FileReader();
reader.onload = function (e) {
var img = document.getElementById("CaptchaImg");
img.src = e.target.result;
};
reader.readAsDataURL(data);
//$('#CaptchaImg').attr('src', data);
}
});
to download an image, and it comes out in binary, looking like this
node.js is returning it as
WriteHeaderMode('image/png', res, 200);
res.end(data, 'binary');
But now, how do I put that into an image tag and show it as an image. Note: I do not want to have return data as base64 encoding, it has to be binary. Im fine with converting the binary into base64 on client side though.
When I pass it to the readAsDataURL, it says TypeError exception.
Thanks
EDIT
var img = document.getElementById("CaptchaImg");
var reader = new FileReader();
reader.onload = function(e) {
//img.src = e.target.result;
$("body").html(e.target.result);
};
reader.readAsDataURL(new Blob([data]));
this seems to convert it into a base64 encoding, which starts as data:application/octet-stream;base64, but doesn't display an image...
jQuery Ajax does not support binary responses(okay now it does), there is a trick that uses overrideMimeType('text/plain; charset=x-user-defined') to return each byte as a character in the response string and then to loop through the response to create a byte array of the data.
However with bare naked XMLHttpRequest this can be done easily with use of the responseType property.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
var img = document.getElementById("CaptchaImg");
var url = window.URL || window.webkitURL;
img.src = url.createObjectURL(this.response);
}
}
xhr.open('GET', 'template/bump1/purse.png');
xhr.responseType = 'blob';
xhr.send();
Musa's answer is a great solution, I implemented something similar in angular and works great, when you define responseType = 'blob' your response won't be a string anymore, it will be a blob type object.
I just needed to add an extra parameter to the headers object (not sure if it's necessary in jQuery). headers: {'Content-Type': "image/png"},
My full request object:
var request = {
url: "_/get_image_/get",
method:"GET",
headers: {'Content-Type': "image/png"},
responseType: 'blob'
}
Try using new Blob(data, {type : 'image/png'}) instead of new Blob([data])
This will ensure that the media type of the blob is a png.
Source: https://developer.mozilla.org/en-US/docs/Web/API/Blob
Whatever framework/lib you're using:
When getting the image (a File), ask for a BLOB type
Use the following function to create a Blob and get an URL out of it
Set your image src to that URL
Code:
export function fileToImageBase64Url(file: File): string {
const blob = new Blob([file], { type: 'image/png' });
return URL.createObjectURL(blob);
}
If at some point you decide that the image is not useful anymore, don't forget to clean it: URL.revokeObjectURL(yourUrl)