I want to take input values from user like name, address, phone. After entering values I want to generate a doc (ms word doc file), make it available to be downloaded locally on click on button using angularjs. How can I achieve this?
Is it possible at client side or it should be from server side?
<input type='text' ng-model='user.username'/>
<input type='number' ng-model='user.phone'/>
<a href='someX.doc' download>download</a>
in my controller, I want to generate doc file, download it on click of link (download).
This will work
In your HTML add the following Line
<a download='someX.doc' ng-click="downloadMyDoc()" ng-href="{{ url }}" style="cursor: pointer">Download</a>
In your angular file add the following
var app=angular.module("myApp",[]);
app.config(['$compileProvider',
function ($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|blob):/);
}]);
app.controller("homeCtrl",function($scope){
$scope.user={};
$scope.downloadMyDoc=function(){
alert("a");
var user=$scope.user;
var content = 'Username: '+user.username+'phone: '+user.phone;
var blob = new Blob([ content ], { type : 'text/plain' });
$scope.url = (window.URL || window.webkitURL).createObjectURL( blob );
}
});
Related
I have this piece of code on a site that exports the contents of local storage to a file in JSON format.
For some reason it stopped working. I tested it in multiple browsers but it's all the same...
No errors get displayed, yet it doesn't export either.
The different variables seem fine, yet it just isn't exporting.
To be honest I have no clue how to do this differently so any help would be appreciated.
Thx
function exportHistory() {
console.log("started");
var _myArray = JSON.stringify(localStorage , null, 4); //indentation in json format, human readable
var vLink = document.getElementById('exportHistory'),
var vBlob = new Blob([_myArray], {type: "octet/stream"}),
vName = 'working_history_' + todayDate() + '.json',
vUrl = window.URL.createObjectURL(vBlob);
console.log(vLink);
vLink.setAttribute('href', vUrl);
vLink.setAttribute('download', vName );
console.log("finished");
}
<button class="btn btn-outline-secondary btn-sm" id="exportHistory" onclick="exportHistory()">Export History</button >
Here you need to add the download attribute to an anchor tag <a> rather than the clicking button itself. You need to create an anchor tag with display:none and programmatically click it to download the file. Here is an example. Notice the button only used to execute the function and href and download attributes are added to the <a> tag.
function exportHistory() {
console.log("started");
var _myArray = JSON.stringify(localStorage , null, 4); //indentation in json format, human readable
//Note: We use the anchor tag here instead button.
var vLink = document.getElementById('exportHistoryLink');
var vBlob = new Blob([_myArray], {type: "octet/stream"});
vName = 'working_history_' + todayDate() + '.json';
vUrl = window.URL.createObjectURL(vBlob);
console.log(vLink);
vLink.setAttribute('href', vUrl);
vLink.setAttribute('download', vName );
//Note: Programmatically click the link to download the file
vLink.click();
console.log("finished");
}
Now add an empty anchor tag to the DOM.
<button class="btn btn-outline-secondary btn-sm" id="exportHistory" onclick="exportHistory()">Export History</button >
<a id="exportHistoryLink" style="display: none;">Export</a>
I am making angular application with image upload option which has the,
Html :
<label class="hoverable" for="fileInput">
<img [src]="url ? url : avatarImage">
<div class="hover-text">Choose file</div>
<div class="background"></div>
</label>
<br/>
<input id="fileInput" type='file' (change)="onSelectFile($event)">
<button *ngIf="url" (click)="delete()" >delete</button>
<img (click)="uploadPersonaImage($event)" class="avatar-images" src="https://www.w3schools.com/howto/img_avatar.png">
<img (click)="uploadPersonaImage($event)" class="avatar-images" src="https://www.w3schools.com/howto/img_avatar2.png">
Here what i am having is if the user clicks over the image he can select and update whatever image he has in local.
Same way if the user was not interested to update the profile image but interested to select any of the avatar image as per his/her wish which i have given like,
<img (click)="uploadPersonaImage($event)" class="avatar-images" src="https://www.w3schools.com/howto/img_avatar.png">
<img (click)="uploadPersonaImage($event)" class="avatar-images" src="https://www.w3schools.com/howto/img_avatar2.png">
And in ts made something like this,
uploadPersonaImage(e) {
this.url = e.target.src;
}
So on the click function the src that comes from the event.target was set to this.url..
But i need to convert it as file.. Because i need to send it as file to the service call so i need to update the avatar image.
So please help me to convert the avatar image selected/clicked by the user to the file/formdata so that it can be sent to the service as file format and can be updated as user selected image..
Example: https://stackblitz.com/edit/angular-file-upload-preview-85v9bg
You can use FormData to attach the read file and send to the API.
onSelectFile(event) {
if (event.target.files && event.target.files[0]) {
this.uploadToServer(event.target.files[0]);
... rest of the code
}
uploadToServer(file) {
let formData: FormData = new FormData();
formData.append('fileName', file);
// call your api service to send it to server, send formData
}
EDIT:
Try this out if you have no option to touch onSelectFile() or trigger a different function when you upload the file.
_url = ''
set url(val) {
this._url = val;
if (val) {
this.dataURLtoFile(val);
}
}
get url() {
return this._url;
}
uploadedImage: File ;
dataURLtoFile(dataurl) {
const arr = dataurl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const imageExtension = mime.split('/')[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
this.uploadedImage = new File([u8arr], `uploaded.${imageExtension}`);
}
On your API call, maybe when you click on a button,
uploadPersonaImage(e) {
// this.apiService.someMethod(this.uploadedImage);
}
If you want to trigger the API call just when you upload the image, add the code of dataURLtoFile() to uploadPersonaImage() and call uploadPersonaImage() from url setter
Clarification
Do you understand what does event.target.src mean (considering e as event)?
Here event means the click/change event you triggered when you
clicked onto upload photo.
event.target means the DOM element on which the event took place.
event.target.src will give you the src attribute value of the
DOM element on which you triggered the change event.
Now, you say won't it work? No, it won't because the element which you clicked is an HTMLInputElement but the src resides under the image in under the label tag. And how are you intending to call uploadPersonaImage()? what calls your method? You haven't answered that even after asking so many times.
In my last edit, I have added code under the setter of the url which will convert the dataUrlFile to an actual File, It completely depends on your server how you want to store the file. As a file or as a dataUrl? If you want to send it as a file then follow the conversions I added in the answer if you want to save as dataUrl then directly save the content of this.url on your API call.
Id like to implement a UI where the user selects an image and that image is instantly displayed back to them for review. The user would have to click "submit" to upload/save the image to their profile.
I am having issues with the "instantly display back to the user part".
I am using angular FormData with the following markup & controller:
MARKUP
<input id="chooseFile" type="file" file-model="picFile" />
<img src="{{uploadedImage}}" /> <!-- this populates with filename but what is the path?? -->
CONTROLLER
angular.element('#chooseFile').change(function(){
var file = $scope.picFile; // this comes up "undefined" since file is still uploading when this is fired
$scope.uploadedImage = file.name;
});
I have 2 primary issues with the above code (described in comments):
1) In the controller, file comes up undefined obviously because even the smallest file takes >0s to upload while the callback is fired pretty much instantaneously. I got it work using $timeout but thats a bit of a lame hack. How can I have the callback wait until the file is uploaded??
2) The idea is to upload the file and display it in the img tag using Angular's data-binding. This works in that src is populated with the filename, but what is the path of the img. Some temporary location in cache or something?? Obviously I havent set a path to move the file yet.
Any help appreciated!
I also needed this feature, some how I manage to display image instantly.
angular.module('HelloWorldApp', [])
.controller('HelloWorldController', function($scope) {
$scope.uploadavtar = function(files) {
//var fd = new FormData();
//Take the first selected file
//fd.append("file", files[0]);
var imagefile = document.querySelector('#file');
if (imagefile.files && imagefile.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#temp_image')
.attr('src', e.target.result);
};
reader.readAsDataURL(imagefile.files[0]);
this.imagefile = imagefile.files[0];
}else{
console.log("Image not selected");
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="HelloWorldApp">
<div ng-controller="HelloWorldController">
<input type="file" id="file" onchange="angular.element(this).scope().uploadavtar(this.files)"/>
</div>
<img src="" id="temp_image" width="100">
<div>
</div>
</div>
I was using laravel + Angularjs so another related post to store image is : https://stackoverflow.com/a/34830307/2815635
this is my xml file:-
<child_2 entity_id="2" value="Root" parent_id="1">
<child_4 entity_id="4" value="Activities" parent_id="2">
<child_10066 entity_id="10066" value="Physical1" parent_id="4">
<child_10067 entity_id="10067" value="Cricket" parent_id="10066">
<child_10068 entity_id="10068" value="One Day" parent_id="10067"/>
</child_10067>
</child_10066>
<child_10069 entity_id="10069" value="Test2" parent_id="4"/>
<child_10070 entity_id="10070" value="Test3" parent_id="4"/>
<child_10071 entity_id="10071" value="Test4" parent_id="4"/>
<child_10072 entity_id="10072" value="Test5" parent_id="4"/>
<child_5 entity_id="5" value="Physical" parent_id="4"/>
</child_4>
</child_2>
this is my javscript:-
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var xml;
$.get(
"region.xml",
function(data)
{ xml=data; },
"html"
);
function get_list(){
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$title = $xml.find('[entity_id="'+$('#select').val()+'"]');
$nodes = $title.find('*');
var result='';
$nodes.each(function(){
result += $(this).attr('entity_id');
result += ',';
});
$("#result").html(result);
}
</script>
<input type="text" id="select">
<input type="button" name="button" value="Search" onclick="get_list()" >
<div id="result">
</div>
here i am try to get all the xml attribute value i am success on them now i want to save this output as a textfile
how its possible
please help me out with this...
thanks
One HTML5 way of doing it:
window.URL = window.URL || window.webkitURL;
function download(/*string*/dataToDownload, /*string*/filename) {
var a = document.createElement('a');
var blob = new Blob(dataToDownload, {'type':'application\/octet-stream'});
a.href = window.URL.createObjectURL(blob);
a.download = filename;
a.click();
};
You can also use Downloadify library, that uses flash to trigger the download and allow the user to name the file.
Or the most common and safe way is to send the data to php and return it with the correct headers that will trigger the download and also allow the user to name the file
Have a look on
File System API of HTML5
File Writer API link
Writing to a file on client side is not only quite complicated (use ActiveX Scripting.FileSystemObject), but is also a bad practice due to security reasons.
If you want a solution that works cross browser, it's better to post the data to server, to a PHP file for example. This php file can then "offer" the file to download.
See this question to get started: How to force file download with PHP.
is it possible to validate file image size with jquery class orjavascript ?
Can i do that ? I made some research but did not reach anything
Thank you
If you want to check image file being uploaded on client side, check HTML5 File API. Here are some samples at:
http://www.html5rocks.com/en/tutorials/file/dndfiles/
You can get file size, find it's type and access binary content.
I was using File API to read EXIF headers from image without uploading image to server.
Here is a source code:
https://gist.github.com/980275/85da4a96a3bb23bae97c3eb7ca777acdea7ed791
Try this:
<input type="file" id="loadfile" />
<input type="button" value="find size" onclick="Size()" />
Script:
function Size() {
if ( $.browser.msie ) {
var a = document.getElementById('loadfile').value;
$('#myImage').attr('src',a);
var imgbytes = document.getElementById('myImage').fileSize;
var imgkbytes = Math.round(parseInt(imgbytes)/1024);
alert(imgkbytes+' KB');
}else {
var fileInput = $("#loadfile")[0];
var imgbytes = fileInput.files[0].fileSize; // Size returned in bytes.
var imgkbytes = Math.round(parseInt(imgbytes)/1024);
alert(imgkbytes+' KB');
}
}