am trying to add functions to my existing Angular project.
I need to add features like upload , download , rename or delete json file.
So I need some advice , for the easy way to do that because am new and learning typescript and angular.
Can you please guide me
Thank you
I can answer download
There are three steps you need to do
1- Issue the proper request from angular side
download(): Observable<HttpResponse<Blob>> {
return this.http.get<Blob>(someURL, {
observe: 'response',
responseType: 'blob'
});}
2- At your backend you need to set the proper headers with response, this snippet of code works with .net4.7 to return csv file contents
var contents = new byte[0]; //set your file contents at this line
var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new
ByteArrayContent(contents)};
response.Content.Headers.ContentDisposition = new
ContentDispositionHeaderValue("attachment")
{
FileName = file.Name
}
response.Content.Headers.Add("Access-Control-Expose-Headers", "Content-
Disposition");
response.Content.Headers.ContentType = new MediaTypeHeaderValue ("text/csv");
return response;
3- Finally subscribe to the http request at angular side
const result
= this.service.download()
.subscribe(res=> {
let contentDisposition = res.headers.get('content-disposition');
let filename = contentDisposition.split(';')[1].split('filename')
[1].split('=')[1].trim();
let blob = res.body;
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(url);
link.parentNode.removeChild(link);
});
Related
I am new to angular. Actually I want to upload a file as a byte array from "angular" to "wepapi"
I can find the codes to upload file from "angular" to "wepapi"
like below code
onFileSelected(event) {
const file:File = event.target.files[0];
if (file) {
this.fileName = file.name;
const formData = new FormData();
formData.append("thumbnail", file);
const upload$ = this.http.post("/api/thumbnail-upload", formData);
upload$.subscribe();
}
}
How can I sent a file as a "byte" array instead of "formData"
Kindly suggest some ideas.
I want to make an <a> tag where it the click function will execute a function called downloadFile() in the typescript file so it will download a log file. instead of downloading the log file, it downloads the link to the log file which does work, but I want to have the download display the actual log information.
downloadFile() {
const blob = new Blob(['blablabla.log'], {type: 'text/log'});
const dataURL = window.URL.createObjectURL(blob);
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob);
return;
}
const link = document.createElement('a');
link.href = dataURL;
link.download = 'export file.log';
link.click();
setTimeout(() => {
window.URL.revokeObjectURL(dataURL);
}, 100);
}
That is not the way to download a file on click from a Blob. Here's how you should proceed:
Create some blob with some file content and some type
Create an URL object. You'll pass this value to an <a> href attribute
Create an <a> and set its download attribute to the desired file name
Make the element non-visible, add it to the DOM, and click on it
Example below:
const downloadFile = () => {
const blob = new Blob(
['Some file content'],
{type:'text/log'}
);
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href=url;
a.download='some-file-name.log';
a.style.display='none';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
}
<a onclick="downloadFile()">Click me!</a>
I am working on PDF view and download for my angular app, here i would want to download pdf on a section, but before that i want to display the pdf on my angular template, which i am stuck at, how could i accomplish this, kindly request assistance, thanks in advance.
This is the code i am using for download, how could i change this so i could even make it viewable on my UI.
onSubmitPolicyPDF() {
let formValuePolicyPDF: any = {
cst_policy_number: this.submitprop.data.policy_number,
}
this.policyService.policyPDF(formValuePolicyPDF)
.pipe()
.subscribe(poldownloaddata => {
this.poldownloaddata = poldownloaddata,
console.log('poldownloaddata: ', poldownloaddata);
console.log(atob(this.poldownloaddata.data.pdf_ccnt));
const linkSource = 'data:application/pdf;base64,' + this.poldownloaddata.data.pdf_ccnt;
// const linkSource = (atob(this.previewdata.data.pdf_ccnt));
const downloadLink = document.createElement("a");
const fileName = "policy.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
(error: any) => this.errorMessage = <any>error
}
)
}
Say I've got a reference to a html file as a Blob b and I create a URL for it, url = URL.createObjectURL(b);.
This gives me something that looks like blob:http%3A//example.com/a0440b61-4850-4568-b6d1-329bae4a3276
I then tried opening this in an <iframe> with a GET parameter ?foo=bar, but it didn't work. How can I pass the parameter?
var html ='<html><head><title>Foo</title></head><body><script>document.body.textContent = window.location.search<\/script></body></html>',
b = new Blob([html], {type: 'text/html'}),
url = URL.createObjectURL(b),
ifrm = document.createElement('iframe');
ifrm.src = url + '?foo=bar';
document.body.appendChild(ifrm);
// expect to see ?foo=bar in <iframe>
DEMO
I don't think adding a query string to the url will work as it essentially changes it to a different url.
However if you simply want to pass parameters you can use the hash to add a fragment to the url
ifrm.src = url + '#foo=bar';
http://jsfiddle.net/thpf584n/1/
For completeness sake, if you want to be able to reference a blob that has as question mark "query string" indicator in it, you can do so in Firefox any way you choose, such as: blob:lalalal?thisworksinfirefox
For Chrome, the above will not work, but this will: blob:lalalla#?thisworksinchromeandfirefox
And for Safari and Microsaft, nothing really works, so do a pre test like so, then plan accordingly:
function initScriptMode() {
var file = new Blob(["test"], {type: "text/javascript"});
var url = URL.createObjectURL(file) + "#test?test";
var request = new XMLHttpRequest();
request.responseType = responseType || "text";
request.open('GET', url);
request.onload = function() {
alert("you can use query strings")
};
try {
request.send();
}
catch(e) {
alert("you can not use query strings")
}
}
If you are doing this with a Javascript Blob for say a WebWorker then you can just to add the parameters into the Blob constructor as a global variable:
const parameters = 'parameters = ' + JSON.stringify({foo:'bar'});
const body = response.body; // From some previous HTTP request
const blob = new Blob([parameters, body], { type: 'application/javascript' });
new Worker(URL.createObjectURL(blob));
Or more general case just store the original URL on the location object
const location = 'location.originalHref = "' + url + '";';
const body = response.body; // From some previous HTTP request
const blob = new Blob([location, body], { type: 'application/javascript' });
new Worker(URL.createObjectURL(blob));
You could also do this with HTML if you can add them say to the root <HTML> tag as attributes or use the <BASE> element for the url or insert them as a script tag but this would require you to modify the response HTML rather then just prepend some extra data
I'm using HTML5 drag&drop to get images from a user's computer and want to upload them to my Rails server (using Carrierwave on that end). I don't know exactly what I'm doing here, but cobbled together this code from these instructions http://code.google.com/p/html5uploader/wiki/HTML5Uploader
This returns a 500 error - can anyone take a look and help me out with what I'm doing wrong?
var files = e.dataTransfer.files;
if (files.length){
for (var i = 0; i<files.length; i++) {
var file = files[i];
var reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function() {
var bin = reader.result;
var xhr = new XMLHttpRequest();
var boundary = 'xxxxxxxxx';
xhr.open('POST', '/images?up=true&base64=true', true);
xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
xhr.setRequestHeader('UP-FILENAME', file.name);
xhr.setRequestHeader('UP-SIZE', file.size);
xhr.setRequestHeader('UP-TYPE', file.type);
xhr.send(window.btoa(bin));
};
};
};
There are a couple of things that could be the culprit. You're reading the file as a binary string, then creating a multipart request, then sending a base64 encoded value.
There's no need to read the file or mess with base64 encoding. Instead, just construct a FormData object, append the file, and send that directly using xhr.send(formData). See my response here.