I use spring boot and I use this code to generate pdf document.
#GetMapping(value = "/members/{memberId}/contract/{contractId}/generalcontracts", produces = "application/pdf")
public ResponseEntity<byte[]> getMemberContract(#PathVariable("memberId") Long memberId, #PathVariable("contractId") Long contractId) throws IOException {
byte[] content = reportService.generateMemberContractReport(contractId);
return prepareReport(content);
}
private ResponseEntity<byte[]> prepareReport(byte[] content) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = "report.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(content, headers, HttpStatus.OK);
return response;
}
In js, I do
<button id="memberPrintReport" type="button" class="btn btn-primary">Imprimer</button>
$("#memberPrintReport").on('click', function (e) {
tryit(getHostName() + "/members/" + memberId + "/contract/" + contractId + "/generalcontracts");
}
function tryit(urlServer) {
var win = window.open('_blank');
downloadFile(urlServer, function (blob) {
var url = URL.createObjectURL(blob);
win.location = url;
});
}
A new tab open, I see during a few second a white label error and after I see the pdf.
I don't understand why I get during a few instant this white label error
Image of the white label error
https://imagebin.ca/v/3Wnqxfpq1yR6
edit:
function downloadFile(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader("Authorization", "Basic " + $.cookie('authorization'));
xhr.responseType = "blob";
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (success)
success(xhr.response);
}
};
xhr.send(null);
}
Edit
that work with chrome, but not with firefox
function tryit(urlServer) {
downloadFile(urlServer, function (blob) {
var url = URL.createObjectURL(blob);
window.open(url, '_blank');
});
}
Your are executing this line: var win = window.open('_blank'); which result in opening http://localhost:8080/_blank, as javascript understand _blank as url. so you need to update your tryit function to this:
function tryit(urlServer) {
downloadFile(urlServer, function (blob) {
var url = URL.createObjectURL(blob);
window.open(url,'_blank');
});
}
Related
I need to upload a image(jpg||png||jpeg) to the server I created with node js.
I have the router and the requestHandlers.. that redirect to this function:
function reqUpload(request, response) {
var form = new formidable.IncomingForm();
form.parse(request, function (error, fields, files) {
lastFileUploaded=files.up.originalFilename;
if (files.up.originalFilename.match(/\.(jpg|jpeg|png)$/i)) {
//check if alredy exists
fs.access(files.up.originalFilename, fs.F_OK, (err) => {
if (err) {
fs.rename(files.up.filepath, files.up.originalFilename, function (err) {
if (err) {
fs.unlink(files.up.originalFilename);
fs.rename(files.up.filepath, files.up.originalFilename);
}
var data;
fs.readFile('./html/std.html', 'utf8', function (err, data) {
if (err) {
console.error(err);
return
}
response.writeHead(200, { "Content-Type": "text/html" });
response.write(data);
response.end();
});
})
}else{
console.log("Already exists, replacing it!");
fs.rename(files.up.filepath, files.up.originalFilename, function (err) {
if (err) {
fs.unlink(files.up.originalFilename);
fs.rename(files.up.filepath, files.up.originalFilename);
}
})}
});
} else {
console.log("format not accepted! try again.");
}
This is working if I upload my file via a button and the form action ="/reqUpload"
however, I need to load in the same page.
How do I do it with ajax + jquery?
I need to display the image uploaded in the same page I uploaded it, without refreshing the page.
I have this function:
function loadPhoto(e){
alert("entered")
var xhr = new XMLHttpRequest();
xhr.open('POST', '/reqUpload');
xhr.onload = function(){
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
alert(this.responseText)
document.getElementById('#photo').innerHTML = this.responseText;
}
xhr.send('/html/std.html');
e.preventDefault();
}
but it breaks and returns this:
enter image description here
seems not to send the file in the correct format, or smth like that
This resolved my case
function loadPhoto(e){
e.preventDefault();
//forming images
var formData = new FormData( document.getElementById("uploading") );
for(var i = 0; i < document.getElementById("up").files.length; i++) {
console.log(i)
formData.append("up[]",document.getElementById("up").files[i]);
}
var filename = document.getElementById('up');
alert(filename)
filename = filename.files[0].name;
alert(filename)
var xhr = new XMLHttpRequest();
xhr.open('POST', '/reqUpload');
xhr.onload = function(){
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
alert(this.responseText)
document.getElementById('#photo').innerHTML = this.responseText;
}
xhr.send(formData);
}
Hello community I hope you can help me since I could not show a message to the user after downloading an excel file.
I am using httpRequest for sending data to the server and everything works correctly the file is downloaded but what I also want is to show the message.
Thank you very much for your help.
This is my code javaScript.
function download_excel_file() {
var file_name; //Example Test.xlsx
var parameter = '{file_name:"' + file_name + '"}';
var url = "Download.aspx/Download_File";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
var a;
if (xhr.readyState === 4 && xhr.status === 200) {
a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response);
a.download = file_name;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
// Here I want to show the message with the legend = File downloaded successfully but it does not work.
$("[id*=message_download]").css("display","block");
$("[id*=message_download]").text(xhr.response.Text);
}
};
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.responseType = 'blob';
xhr.send(parameter);
}
<input id="btn_download_file" type="button" value="Download file" class="btn btn-success btn-block" onclick="return download_excel_file();"/>
<div id="message_download" class="p-3 mb-1 bg-secondary text-white text-center" style="display:none"> </div>
This is my code from server.
[WebMethod]
public static void Download_File(string file_name)
{
if (file_name != null || file_name != "")
{
string path = HttpContext.Current.Server.MapPath("~/Folder_Excel/" + file_name);
if (File.Exists(path))
{
// This is the message I want to show in the div $("[id*=message_download]")
HttpContext.Current.Response.Write("File downloaded successfully");
System.IO.FileStream fs = null;
fs = System.IO.File.Open(path, System.IO.FileMode.Open);
byte[] btFile = new byte[fs.Length];
fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
fs.Close();
HttpContext.Current.Response.AddHeader("Content-disposition", "attachment; filename=" + file_name);
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.BinaryWrite(btFile);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
else
{
HttpContext.Current.Response.Write("No files");
}
}
}
Add an ‘alert’ at the end of the script:
<script>
function myFunction() {
alert("Success! File downloaded!");
}
</script>
added 2019 10 04
Use InnerHTML along with getElementById to set the message back from the server.
from https://www.w3schools.com/xml/xml_http.asp
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "filename", true);
xhttp.send();
You should display your message at first, then make the browser "click" on the download button. Otherwise the browser may just fire an unload event and stop executing any scripts at this time - like on redirection.
I don't think you're using the Attribute Contains Selector correctly.
$("[id*=message_download]").css("display","block");
$("[id*=message_download]").text(xhr.response.Text);
Try this instead:
$("[id*='message_download']").css("display","block");
$("[id*='message_download']").text(xhr.responseText);
Or better yet, use $("#message_download") Also notice that I changed xhr.response.Text to xhr.responseText
I am using a Azure speech services to load a TTS from an ajax post.
function tts(data){
var url = "https://speech.platform.bing.com/synthesize"
var headers = {
"X-Microsoft-OutputFormat":"audio-16khz-64kbitrate-mono-mp3",
"Content-Type":"application/x-www-form-urlencoded",
"Authorization":"Bearer " + JWT // My Jason Token
}
$.ajax({
url: url,
type: 'post',
data: data, // The text for speech
headers: headers,
success: function (data) {
audiodata = data;
}
});
}
The audiodata contains the loaded mpeg audio data. How can I put this data into a <audio> HTML tag?
You can use the following Javascript code sample to do that:
function tts(data) {
var url = "https://speech.platform.bing.com/synthesize"
var oReq = new XMLHttpRequest();
oReq.open("POST", url, true);
oReq.responseType = "blob";
oReq.setRequestHeader("X-Microsoft-OutputFormat", "audio-16khz-64kbitrate-mono-mp3");
oReq.setRequestHeader("Content-Type", "application/ssml+xml");
oReq.setRequestHeader("Authorization", "Bearer " + JWT)
oReq.onload = function (oEvent) {
var blob = oReq.response; // Note: not oReq.responseText
if (blob) {
var audioObj = document.getElementById('audiotag');
audioObj.src = window.URL.createObjectURL(blob);
audioObj.play();
}
};
oReq.send(data);
}
And the HTML page should include the content below:
<audio id="audiotag"></audio>
Thank you for reading!
I want to open a PDF from a REST backend that gets loaded via XHR in a new tab with specified filename and Authorization header.
So far I managed to download it with this (incl. auth headers and filename):
// saves XHR stream as file with configurable filename
downloadXHRFile:function(endpoint,data,method,filename,errorcallback,mimetype){
bsLoadingOverlayService.start();
var def = $q.defer();
var token = localStorageService.get('token');
var xhr = new XMLHttpRequest();
xhr.open(method, CONFIG.URL+endpoint, true);
xhr.setRequestHeader('Authorization', 'Bearer '+token);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var blob=new Blob([this.response], {type:mimetype});
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download=filename;
link.click();
bsLoadingOverlayService.stop();
}else{
bsLoadingOverlayService.stop();
errorcallback(xhr.statusText);
}
def.resolve();
};
xhr.send(
JSON.stringify(data)
);
return def;
},
Further I managed to open it in a new tab with the following code (incl. auth headers).
Unfortunately the URL (and by that the filename) looks like this:
blob:http://localhost:3000/0857f080-d152-48c6-b5fb-6e56292db651
Probably it can be solved somehow like above but I cant find the solution.
Does someone have a clever idea how I could set the filename in the new Tab?
// opens XHR filestream in tab
openXHRFile: function(endpoint,filename,errorcallback){
var token = localStorageService.get('token');
var our_url = CONFIG.URL+endpoint;
var win = window.open('_blank');
downloadFile(our_url, function(blob) {
var url = URL.createObjectURL(blob);
win.location = url;
});
function downloadFile(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader("Authorization", 'Bearer '+token);
// xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = "blob";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (success) success(xhr.response);
}else{
}
};
xhr.send(null);
}
},
I have an only JavaScript page and .asmx page. I want to download file
using only JavaScript how can I download the file. I want to download a particular resume.
I am getting resume here,
var res = data[i].resume;
You may use different third-party libraries:
jQuery.fileDownload
It takes URL as an input and downloads a file while shows a loading dialog.
Github: https://github.com/johnculviner/jquery.fileDownload
Demo: http://jqueryfiledownload.apphb.com/
Usage:
$.fileDownload(requestUrl, {
preparingMessageHtml: "Downloading...",
failMessageHtml: "Error, please try again."
});
FileSaver.js
It takes Blob object as an input and downloads it. Blob can be acquired using XMLHttpRequest.
Github: https://github.com/eligrey/FileSaver.js/
Demo: http://eligrey.com/demos/FileSaver.js/
Usage:
var xhr = new XMLHttpRequest();
xhr.open("GET", requestUrl);
xhr.responseType = "blob";
xhr.onload = function () {
saveAs(this.response, 'filename.txt'); // saveAs is a part of FileSaver.js
};
xhr.send();
It may also be used to save canvas-based images, dynamically generated text and any other Blobs.
Or write it yourself
function saveData(blob, fileName) // does the same as FileSaver.js
{
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
}
Now, if it is a text file, you can simply download it, create a blob, and save it:
$.ajax({
url: requestUrl,
processData: false,
dataType: 'text'
}).done(function(data) {
var blob = new Blob([data], { type: "text/plain; encoding=utf8" });
saveData(blob, 'filename.txt');
});
Or you can use XMLHttpRequest which works great for any types of files, including binary:
var xhr = new XMLHttpRequest();
xhr.open("GET", requestUrl);
xhr.responseType = "blob";
xhr.onload = function () {
saveData(this.response, 'filename'); // saveAs is now your function
};
xhr.send();
Here is the working demo. Note that this fiddle downloads a file right after opening it. The file is just a random source file from GitHub.
Actually, There is a javascript library called FileSaver.js, FileSaver.js saving file on the client-side. it can help you achieve this.
here: https://github.com/eligrey/FileSaver.js
Usage:
<script src="http://cdn.jsdelivr.net/g/filesaver.js"></script>
<script>
function SaveAsFile(t,f,m) {
try {
var b = new Blob([t],{type:m});
saveAs(b, f);
} catch (e) {
window.open("data:"+m+"," + encodeURIComponent(t), '_blank','');
}
}
SaveAsFile("text","filename.txt","text/plain;charset=utf-8");
</script>
If you use jQuery you can do some like that:
var getFile = function( path_to_file, callback ) {
$.ajax( {
url: path_to_file,
success: callback
} );
};
getFile( 'path_to_your_asmx_page', function( file_as_text ) {
console.log( file_as_text );
} );
Call getFile and you'll get file content in callback function
Use the code below.
var sampleBytes = base64ToArrayBuffer('THISISTHETESTDATA');
saveByteArray([sampleBytes], 'ashok.text');
function base64ToArrayBuffer(base64)
{
var binaryString = window.atob(base64);
var binaryLen = binaryString.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++)
{
var ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
}
return bytes;
}
var saveByteArray = (function ()
{
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, name) {
var blob = new Blob(data, {type: "text/plain"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = name;
a.click();
window.URL.revokeObjectURL(url);
};
}());