Angularjs - open a PDF in a new tab : customize url - angularjs

I want to display a pdf file in a new tab.
I retrieve the pdf from my server (J2EE/Spring MVC).
When I am getting the response I do :
ReportingLot.FicheStock.get({idLot:vm.lot.id}, function (response) {
var file = new Blob([response.data], {type: 'application/pdf'});
var fileURL = window.URL.createObjectURL(file);
var pdfFile = $sce.trustAsResourceUrl(fileURL);
window.open(pdfFile, '_blank');
});
The pdf displays in the new tab, but the url is :
blob:http://localhost:8080/9e8eb169-afff-4013-9a7a-04c2efdfb7e3
is there a way to custom this ur to make it more understable for the users?
Thanks.
[UPDATE]
Response.setHeader("Content-disposition", "inline; filename=\"ficheStock.pdf\"");
response.setContentType("application/pdf");
ServletOutputStream outputStream = response.getOutputStream();
baos.writeTo(outputStream);
outputStream.flush();

Related

How to save SURVEY PDF on the disk

I want to save somes PDF created with 'survey-pdf' on my disk.
Actually, i can send the PDF but i can't save it on my disk.
My final code :
return surveyPDF.save(filename);
Someone can help me ?
Thank you
Can you try
await surveyPDF.save(filename)
?
.save seems to be an asynchronous function that downloads the PDF file.
From the docs
Call save method of surveyPDF object to download file in browser. This is asynchronous method
#2 If the first method doesn't work, you can try this
function savePdfAsString() {
const surveyPDF = new SurveyPDF.SurveyPDF(json);
surveyPDF.data = survey.data;
surveyPDF
.raw("dataurlstring")
.then(function (text) {
//var file = new Blob([text], {type: "application/pdf"});
var a = document.createElement("a");
//a.href = URL.createObjectURL(file);
a.href = text;
a.download = "surveyAsString.pdf";
//document
// .body
// .appendChild(a);
a.click();
});
}
Here you are using the .raw function to transform the PDF into a dataurlstring and then downloading that. Here's the docs for this
*Not tested

Using TinyMCE uploading images to a backend

I am trying to use the rich text editor TinyMCE for a blog platform I am currently working on.
I am also using React with a Flask backend. A
User should be able to create a blog entry with the editor and also use/ upload images.
I got everything setup but I don't know how to store the images in my backend so you can save a blog with all it's content.
I got this callback function from their documentation but I do not really understand what's happening there and if it is enough to send the file object to my backend and store it in the database.
file_picker_callback: function (cb, value, meta) {
var input = document.createElement("input");
input.setAttribute("type", "file");
input.setAttribute("accept", "image/png , image/jpg");
input.onchange = function () {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function () {
var id = "blobid" + new Date().getTime();
var blobCache =
window.tinymce.activeEditor.editorUpload.blobCache;
var base64 = reader.result.split(",")[1];
var blobInfo = blobCache.create(id, file, base64);
blobCache.add(blobInfo);
/* call the callback and populate the Title field with the file name */
cb(blobInfo.blobUri(), { title: file.name });
};
reader.readAsDataURL(file);
console.log(file);
};
This is the console.log(file) output
File {name: "wlogLogo.png", lastModified: 1590578382000, webkitRelativePath: "", size: 4591, type: "image/png", …}

How to automatically download a xlsx file(in angularjs 1) sent by server

The HTTP response for a POST request that I am getting from server side is a xlsx file.How do I download the file in angularjs 1?
Note: res.download() won't work here,since its a POST request that I am making,and res.download() works only for GET request
The following shall work :
$http.post("url_here", post_data_to_send, {responseType: 'arraybuffer'})
.success(function (data,status,headers) {
var blob = new Blob([data]);
var objectUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
a.style = "display:none";
a.href = objectUrl;
a.download = headers().filename;
a.click();
console.log("Report downloaded");
}).error(function (err) {
console.log(err);
});
You can do it directly on Client Side, you may have some cross-browser compatibility issues (the best way is always to provide a download stream via server, for large files for example).
// this example uses a JSON String
// but you can do it with any valid blob argument
const fileContent = [JSON.stringify(
['something', 'to', 'download'], null, 2
)];
const downloader = document.createElement('a');
// set the filename here
downloader.download = 'filename.json';
const blob = new Blob(fileContent, {type: 'text/plain'});
downloader.href = window.URL.createObjectURL(blob);
// trigger the download
downloader.click();
In my opinion, a redirect to the downloadable resource could be the best choice.

Angular: can't download server side generated spreadsheet

I'm trying to download a server generated spreadsheet.
My application uses Angular on the front-end and Java on the back-end.
Here's the method on the back-end that receives the request to generate and return the file:
#RequestMapping(value = "download", method = RequestMethod.GET, produces = "application/xls")
public ResponseEntity<InputStreamResource> download() throws IOException {
ByteArrayOutputStream fileOut = new ByteArrayOutputStream();
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet = workbook.createSheet("POI Worksheet");
HSSFRow row1 = worksheet.createRow((short) 0);
HSSFCell cellA1 = row1.createCell((short) 0);
cellA1.setCellValue("Hello!");
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.GOLD.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellA1.setCellStyle(cellStyle);
workbook.write(fileOut);
fileOut.close();
byte[] file = fileOut.toByteArray();
return ResponseEntity
.ok()
.contentLength(file.length)
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(new ByteArrayInputStream(file)));
}
And on the front-end, the following function is executed when the user clicks on Download button:
$scope.exportFile = function() {
$http.get('http://127.0.0.1:8000/api/excel/download')
.success(function (data, status, headers, config) {
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:application/octet-stream;charset=utf-8,' + encodeURI(data),
target: '_blank',
download: 'spreadsheet.xls'
})[0].click();
})
.error(function (data, status, headers, config) {
// handle error
});
};
The returned spreadsheet contains unreadable characters.
If I access http://127.0.0.1:8000/api/excel/download directly, the spreadsheet is downloaded without the .xls extension (with no extension at all). If I rename the file adding the .xls extension and then open it, I can see the file contents. So I think the problem it's on the call Angular does to back-end and not on generating the file on Java.
Has anyone experienced this situation or have some example to share? What am I doing wrong?
The Content-Disposition header should do the trick. So, you would have something like this:
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("Attachment", "spreadsheet.xls");
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentLength(file.length);
return new ResponseEntity<InputStreamResource>(
new InputStreamResource(new ByteArrayInputStream(file)),
headers, HttpStatus.OK);

Download a file which does not exists in project directory in AngularJS

In my project i just wanted to implement upload and download features. I have done upload functionality with AngularJS and Node.js. But here the problem is to upload a file(.pdf, all image formats) into somewhere in the system. Say for example, my project is located in D drive. Though i have to upload a file into C drive or some other drive in my computer and i have done it successfully. But when i try to read the file location from Node.js and pass the path to angular, everything is ok and file is downloaded in the browser. when i try to open a downloaded file it sends back a response - fatal error/ nothing to show. I have tried with blob only when i send a filestream instead a path to Angular.
The code is as follows
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
where data is a file stream response from the server.
not my code but try this to save a BLOB:
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
var data = { x: 42, s: "hello, world", d: new Date() },
fileName = "my-download.json";
saveData(data, fileName);
Source: http://jsfiddle.net/koldev/cw7w5/
If you want to force the download of a linked file you could use the HTML5 a option download
<a download="filename_for_download" href="path/to/the/file"> Clicking o will force a download</a>
Some more information: https://developers.google.com/web/updates/2011/08/Downloading-resources-in-HTML5-a-download?hl=en
keep the (not existing) support of older browsers in mind
One Note: Your upload process ("to upload a file into C drive or some other drive in my computer") sounds like it may be improved or rethought.

Resources