I am creating a file on server in a request from client-side. Now, I want to send that file in response to the AJAX response. Below is the JAVA code.
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment; filename=\"Portfolio.pdf\"");
OutputStream output;
try {
output = response.getOutputStream();
output.write(Util.readFileInBytes("/Portfolio.pdf"));
output.close();
} catch (IOException e) {
e.printStackTrace();
}
Now, how to show a "Save As" dialog to user for saving the file. Thanks in advance for the help.The javascript code is as below :
$.ajax({
url : "export",
dataType : 'text',
contentType : 'application/pdf',
success: function() { //code to display "Save As" dialog box to user.}});
Also see this discussion stackoverflow.com/questions/833068/how-to-force-save-as-dialog-box-in-firefox-besides-changing-headers.
You can encode file in base64 string, send it to client and then assign the value to location.href and save dialog will be shown to user.
But it won't work in IE. Don't know what are your requirements.
Related
I want to download a file from the front end. The file is generated in the TestFlow.generateReport method.
My code runs until the end but it doesn't download anything. It just prints the data to the console.log.
What am I missing here?
My backend controller:
#RequestMapping(value = "/flow/generate-report" , method = RequestMethod.GET)
public #ResponseBody void generateFlowReport(#RequestParam("flowName") String flowName, HttpServletResponse response) {
InputStream resource = TestFlow.generateReport(flowName);
response.setContentType("application/force-download");
response.setHeader("Content-Disposition","attachment; filename=report-" + flowName + ".xlsx");
try {
IOUtils.copy(resource,response.getOutputStream());
response.flushBuffer();
resource.close();
} catch (IOException e) {
e.printStackTrace();
}
}
My frontend code:
$('.generateReport').click(function () {
var flowName = $(this).attr('name');
$.ajax({
url: '/flow/generate-report',
type: 'get',
data: {flowName: flowName},
success: function (data) {
console.log(data);
}
})
});
I get HTTP status 200
HTTP/1.1 200
Content-Disposition: attachment; filename=report-tellerFlow.xlsx
Content-Type: application/xlsx
Transfer-Encoding: chunked
Content-Type: application/force-download header might not always work because some browsers/web clients might not support the attachment download.
Try changing to Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet which is the correct XLSX type and then check the documentation for your browser/web client. As per this answer using Ajax to download a file might not won't work in your web client.
I'm not sure that an XHR request can trigger a download dialog on the browser. You might want to spawn a new window instead with the download URL - the browser should detect the content disposition and handle the download accordingly.
If you still want to do it with XHR, you need to use Blobs instead - JavaScript blob filename without link
I have Export to Excel button in my HTML page, onClick of the button i will send GET request to ASP .Net Web API, which which get data from Database and return HTTPContext binary Response. In the front end, i am getting binary data of the Excel file. How to directly download the file once response came?
HttpContext.Current.Response.ClearContent();
FileStream objFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
byte[] excelResponse = new byte[objFileStream.Length];
objFileStream.Read(excelResponse, 0, excelResponse.Length);
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));
HttpContext.Current.Response.BinaryWrite(excelResponse);
My front end binary content
PKS��J�ɉ�fxl/workbook.xml �(��P�N�0����SA5������8�����4�Z^���8�I�n"�+�Y�����|}����ጉ�V,����V�����v��OJ�=�
How to download as file? I dont want to use form
Below is the AJAX call i am making on click on Export button.
// Make AJAX call
$.ajax({
type: "GET",
url: "http://localhost:8899/api/ExportDataToExcel/",
data: oData,
headers: {
"Authorization": "Bearer " + sToken,
},
success: function (oResult) {
onSuccess(oResult);
},
error: function (oResponse) {
onFailure(oResponse);
}
});
That's all i am doing on Export to Excel button click.
If i use Form submit, then i am getting Authorization denied error, as the API expects bearer token. Following code gives Authorization denied error
var form = document.createElement("form")
form.action = url + 'exportDataToExcel/';
form.method = "GET";
document.body.appendChild(form);
form.submit(true);
document.body.removeChild(form);
I resolved the issue by replacing AJAX with XMLHttpRequest, as AJAX can't receive binary buffer response. Once i received response for XHR, i am creating JavaScript Blob and then anchor tag and redirecting that anchor element to BlobObjectURL.
Hi Here my Sql Table
I want to download those files using java script . I get Record from "ID" to my java script . I want to download those files, how can i do that
here is the my script get file by ID
function DownloadFile(e) {
$.ajax({
dataType: 'JSON',
url: '/api/FileAttachment/GetFileByID',
async: false,
data: { id: e },
success: function (data) {
downloadPDFfile(data);
}
});
}
function downloadPDFfile(a) {
// I want write download code here
}
If you want to download a file from server, at first create a url request like this:
function downloadPDFfile(param) {
var downloadUrl = http://www.yourhost.com/download?id=param
window.open(downloadUrl);
}
At your server, write code to receive this request, get requested param(s), read your binary data from db then response this data to client as a stream and the browser will do it's job.
Dont't forget to specify HTTP response header fields. For example:
Content-Type: text/html /* MIME type */
Content-Disposition: attachment; filename="fname.ext" /* Using 'attachment' option to raise a "File Download" dialogue box */
I'm trying to upload images to parse and later attach them to models, however whenever I upload one it returns as a successful upload but the url contains a broken image link.
for instance:
http://files.parse.com/aac0413c-eada-4602-9451-2ee5da7d1241/22eaa50b-1e61-4744-abf9-a57ba9f4123f-test.jpg
Here's the upload code:
getImg: ->
CameraHelper.fileUpload (file) =>
#file = file
forge.file.URL file, (url) =>
#fileURL = url
#$("#uploadImg").addClass("fadeIn").css("background-image", "url(#{url})")
#$("#removeImg").css("display", "inline")
, (content) ->
error "Error finding Image"
, ->
debug "Upload Cancelled"
serverUrl = 'https://api.parse.com/1/files/test.jpg'
parseFile = _.extend #file,
type: "image/jpeg"
name: "share.jpg"
$.ajax
type: "POST",
beforeSend: (request)->
request.setRequestHeader "X-Parse-Application-Id", 'MY-APP-ID'
request.setRequestHeader "X-Parse-REST-API-Key", 'MY-REST-API-ID'
request.setRequestHeader "Content-Type", "image/jpeg"
url: serverUrl
data: parseFile
processData: false
contentType: false
success: (data) ->
alert "File available at: " + data.url
error: (data) ->
obj = jQuery.parseJSON(data)
alert obj
CameraHelper =
fileUpload: (success, err) ->
if APP
forge.file.getImage
saveLocation: "file"
source: "camera"
height: "620px"
width: "620px"
, (file) ->
debug "Successfully uploaded img"
success?(file)
, (content) ->
error "Error in uploading img", content
err?()
else
debug "Sorry that feature is not currently available on the mobile web."
CameraHelper
NOTE: I'm using triggerIO, also referenced: https://www.parse.com/questions/uploading-files-to-parse-using-javascript-and-the-rest-api to no avail
parseFile is the image I'm trying to upload
I'm not sure exactly what Parse are expecting in the POST body, but I think they want the entire body to be the image data, with no multi-part encoding.
That means you need to do two things:
Firstly, when uploading files, you should use the files parameter, rather than data. See https://trigger.io/docs/current/api/modules/request.html#forgerequestajaxoptions. This is true whenever you're uploading files, not just with Parse.
Secondly, as I think Parse don't want an encoded POST body, use the fileUploadMethod: "raw" parameter to just dump the image data directly into the request.
I have an ajax call that successfully calls a page that by itself works fine. You click the button, and a PDF downloads. However, when I make an AJAX call using the same request type and url, the data is returned, but does not prompt a download.
My call :
$("#download-pdf").live('click', function(){
$.ajax({
url: $(this).parents('form').attr('action'),
type: 'POST',
success: function(data){
console.log(data);
}
});
return false;
});
Data is returned as what would be an unparsed PDF. So I know the information is there. It just doesn't cause a download. Any tricks?
The only way to force a download is to refresh the page using the "standard" form submission method. With Ajax you'll receive the raw output data (PDF) and no save dialog will ever pop up
It's not possible to force downloading when using AJAX.
Please read this: Force download a pdf link using javascript/ajax/jquery
If you would just submit the form then you can tell the browser to download the file by sending the appropriate headers:
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=file.pdf");
Response.ContentType = "application/pdf";
Response.WriteFile(Server.MapPath(#"~/file.pdf"));
Response.End();