image download using angular js net work error - javascript

I am trying to download image using below code. But file showed as download with error
(Failed - Network error)
I am using below code
$scope.downloadDocument = function (doc) {
$http({
method: "GET",
url: appConfig.apiUrl + "/downloadDoc/" + $scope.array.nic + "/" + doc.fileName
}).then(function (response) {
console.log(response);
$scope.downloadedImage = response.data;
var a = document.createElement("a"); //Create <a>
a.href = "data:image/jpge;base64," + response.data; //Image Base64 Goes here
console.log(a);
a.download = doc.fileName; //File name Here
a.click(); //Downloaded file
}, function (response) {
$log.log(response);
});
}
My response
When I click download button. It shows as download with error. Check below image
How i do this correctly. please help

You need to add responseType:'blob' your request,
also I prefer use object url (https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL) for downloading files
function downloadBlob(blob, name) {
const data = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = data;
link.target = '_self';
link.download = name;
link.dispatchEvent(
new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window
})
);
setTimeout(() => {
window.URL.revokeObjectURL(data);
link.remove();
}, 100);
}
$scope.downloadDocument = function (doc) {
$http({
method: "GET",
url: appConfig.apiUrl + "/downloadDoc/" + $scope.array.nic + "/" + doc.fileName,
responseType: 'blob'
}).then(function (response) {
console.log(response);
downloadBlob(new Blob([response.data]), doc.fileName);
}, function (response) {
$log.log(response);
});
}

Related

Unable to select text in pdf when downloading from NGINX server

I have the following code in a NodeJS app using the library node-html-pdf:
pdf.create(PDF_html).toStream((err, pdfStream) => {
if (err) {
console.log(err)
return res.sendStatus(500)
} else {
res.statusCode = 200
res.setHeader('Content-type', 'application/pdf')
res.attachment()
pdfStream.on('end', () => {
return res.end()
})
pdfStream.pipe(res)
}
})
On the client side I am using fetch to retrieve and download the PDF using the following code:
document.getElementById('pdf_button').addEventListener("click", function() {
let query_nr = ''
let query_spnr = ''
let url = 'https://{my.public.server.url}/getPDF/'
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
"nr": query_nr,
"spnr": query_spnr
})
})
.then((response) => response.blob())
.then((blob) => {
blob = new Blob([blob], {type: "application/pdf"});
const objectURL = URL.createObjectURL(blob);
const a = document.createElement("a")
document.body.appendChild(a)
a.style = "display: none"
a.href = objectURL
a.type = 'application/pdf'
a.download = query_nr + '-' + query_spnr + '.pdf'
console.log(a);
a.click()
// window.open(objectURL, '_blank');
})
.catch((error) => {
console.error(error);
})
});
The above code works fine as long I am using localhost as url, and I am able to select text from the downloaded text.
When I download the PDF from the server it seems like the whole PDF-file gets converted to an image (I might be very wrong), and I am not able to select any text.
Does anyone know how I can fix this? And why is this happening?

How to open PDF in a new tab from Cloud without downloading it in local machine

I am trying to open a PDF file in a new tab and want to read file without downloading it in local machine.
I tried this function, but it is not loading my pdf and giving error can not load pdf
function readFileInNewTab (fileId) {
let url = BASE_URL + "api/CMS/Documents/Download/" + fileId;
const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/pdf', ...authHeader(url) },
credentials: 'include',
responseType: "blob", // important
};
inProgress = true;
return fetch (url, requestOptions).then(handleResponse)
.then((response)=> {
const file = new Blob([response], { type: "application/pdf" });
//Build a URL from the file
const fileURL = URL.createObjectURL(file);
//Open the URL on new Window
debugger
const pdfWindow = window.open();
pdfWindow.location.href = fileURL;
})
.catch((error) => {
console.log(error);
});
} ```

How can we download an XML file through ajax in ASP mvc?

This is my Controller code for returning the XDocument file. I turn it into a MemoryStream then return it as base 64 string.
[HttpPost]
public ActionResult ImportAcesFileAjax(TransactionViewModel transactionViewModel)
{
XDocument xDocument = new XDocument();
try
{
if (transactionViewModel.File.IsNotNullObject())
{
ImportService importService = new ImportService();
xDocument = importService.ProcessExcelFileForTransformation(transactionViewModel);
_logger.Information($"Finished processing {transactionViewModel.File.FileName}");
}
}
catch (Exception e)
{
_logger.Error($"Error: {e.Message}");
_logger.Error(e.StackTrace);
throw;
}
return ReturnImportXmlAsByte(xDocument, "import.xml");
}
protected ActionResult ReturnImportXmlAsByte(XDocument xDocument, string xmlFilename)
{
using (MemoryStream stream = new MemoryStream())
using(XmlWriter xmlWriter = XmlWriter.Create(stream))
{
xDocument.WriteTo(xmlWriter);
var byteLength = stream.ToArray().Length;
var base64String = Convert.ToBase64String(stream.ToArray(), 0, byteLength);
return Json(new {base64String = base64String, xmlFilename = xmlFilename});
}
}
I use the following code in the front end:
$.ajax({
url: requestUrl,
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function (excelByteResult) {
var bytes = base64ToBytes(excelByteResult.base64String);
var blob = new Blob([bytes], { type: "text/xml" });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = excelByteResult.xmlFilename;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("Xhr: " + jqXHR.responseText);
console.log("Status: " + status);
console.log("Error Thrown: " + errorThrown);
}
});
The ajax call is successful but I can't seem to access the file. Are there any alternatives to my approach we may work? The requirement is to download an xml file via ajax

Download a PNG file served as binary/octet-stream

steps that will reproduce the problem :
I am saving a Blob object as form data using a service and I am receiving the response as content-type: application/octet-stream as in attached image
What is the expected result?
To download and view the the application/octet-stream as a image into local machine and view it using applications
What happens instead?
able to download the file as image but it says we dont support this file format though its (ex:image.png)
function add() {
$.ajax({
url: 'https://localhost:3000/upload/sampleImage.png',
type: 'GET',
success: function (data) {
const link = document.createElement('a');
link.style.display = 'none';
link.download = "sample image";
link.href =
'data:' +
'image/png' +
';base64,' +
window.btoa(unescape(encodeURIComponent(data)));
link.click();
},
error: function (request, error) {
alert("Request: " + JSON.stringify(request));
}
});
}
Any ways to download the file and preview it successfully
Set the responseType as blob in request
Using HttpClient:
this.http.get("https://localhost:3000/upload/sampleImage.png",{responseType:'blob'}).subscribe((img)=>{
const link = document.createElement('a');
link.style.display = 'none';
link.download = "sample image";
link.href =window.URL.createObjectURL(data);
link.click();
});
Now using $.ajax(not recommended,avoid using it) specify the dataType as blob and use window.URL.createObjectURL(data) to create URL
$.ajax({
url: 'https://localhost:3000/upload/sampleImage.png',
type: 'GET',
xhrFields:{
responseType: 'blob'
},
success: function (data) {
const link = document.createElement('a');
link.style.display = 'none';
link.download = "sample image";
var blob = new Blob([data], {type: 'image/png'});
link.href =window.URL.createObjectURL(blob);
link.click();
},
error: function (request, error) {
alert("Request: " + JSON.stringify(request));
}

How to convert the byte code to zip file in javascript

Im using the following code to convert the byte code to zip file but it does not download the actual xml and asc file send in the response , instead it just donwloads the standard zip contents , im not aware where i am going wrong , can anyone help me with this,
$http({
url:url,
method: requestType,
data:requestBody?requestBody:"",
headers: {
'Content-type': "application/json",
"SessionID":$rootScope.token
},
responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
let blob = new Blob([data], {type: "application/zip"});
let objectUrl = URL.createObjectURL(blob);
let link = document.createElement('a');
link.href = objectUrl;
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
$scope.exp = {}; // to reset the export form after submit.
$scope.surveyReportdownloading = false;
$scope.tabActive = false;
}).error(function (error) {
//upload failed
console.log(error);
});
this is not downloading the actual files at all. Can anyone help me through this. The byte cod ethat backend team is sending is as follows.
"PK:8xJMÆVÞ|xl/workbook.xml ¢( ÍnÂ0ïúÖ>#MpR­¸{C,²vdѾ}CR¢¶'n;³³fË«u磵göI­ñ«  ¡+8÷²AþÅvhú]mÐKwⶮµÄBxEwØ ­ñî<´GX¾s(oµ#6°|~b¬¼5;h¼úAöƽîÍd|ñ¿©rMbFVð~!îØ`nT10Wè~Ø4SäiÅÑ,ÇWøÁÿC|¼í¶ëÃzûL/ó4KËYZG0U:üþÂòPK:8xJnmt?Ø[Content_Types].xml ¢( ÅMNÃ0¯y·] vl¡\À²'ÕøGIiÏÆ#q& TUЪº²lÏ{ßõä·÷é|ãl
mð¥#×ÁX¿,EKU~#æ³éË6f\ê±5Q¼u
Na"x¾©Brx2*½RKÑèZêà <åÔyÙôÕ6=løxÀ²\dwC]±±Z_˵7¿ y¨*«ÁÝ:(5¹¦è×Â)ë¯zc¹ Áã _S¬ìk°¶w'~Äd
dèQ9öF¾´êBÙ/ãâ¼ÃîüÿkiÛ>þfå"Ç㿽Sç =ÉÞ']d£áºE
îdþ`s(}Oâ&K\­gJü=x?½wÈþ}PK
38xJ£ ²×rels/.rels ¢( ï»¿PK:8xJILE#¥¶xl/worksheets/sheet1.xml ¢( ¥ÛrÇEÅ÷èn\U\¡\q®ª%^ÿþõ˯ûÃ/·W»Ýñìÿ|"
Any help is appreciated. Thanks!
Seems like the issue is with the type parameter try with the below code
You can access the content-type from headers.
If it doesn't work, try with application/zip, application/octet-stream
$http({
url: url,
method: requestType,
data: requestBody ? requestBody : "",
headers: {
'Content-type': "application/json",
"SessionID": $rootScope.token
},
responseType: 'arraybuffer'
}).success(function(data, status, headers, config) {
let blob = new Blob([data], {
type: headers['content-type']
// OR
// type:"application/zip, application/octet-stream"
});
let objectUrl = URL.createObjectURL(blob);
let link = document.createElement('a');
link.href = objectUrl;
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
$scope.exp = {}; // to reset the export form after submit.
$scope.surveyReportdownloading = false;
$scope.tabActive = false;
}).error(function(error) {
//upload failed
console.log(error);
});
var blob = new Blob([response.data],{type:headers['content-type']});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "Filename";
link.click();

Categories