Download Binary data file from java script - javascript

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 */

Related

Send request to download a zip file from server via Ajax in Laravel

I am using Laravel 5.7 and I want to download zip files on request basis. I send the request to the server via Ajax (the following code), and it returns 200 OK, but does not download the zip file (I can see the content of the zip file in the console though). Also, when I make a regular request (using form to submit the request) it downloads the zip file (as expected), but not with the Ajax request. The reason which I want to use Ajax is to add loading spinner during the downloading the files. Am I missing anything here?
$.ajax({
url: "my_url",
type: 'POST',
async: true,
beforeSend: function() {
$("#loading").show();
},
data: { selectedIds: ids },
success: function(result) {
//
},
complete:function(result) {
$("#loading").hide();
}
});

AJAX request to XML in GZIP/ZIP format - How do I decompress data in Javascript

I'm trying to fetch XML data but I'm unable to use it as I don't know how to decompress the data. I have two options I can either use GZIP or a ZIP file from the data provider.
$(document).ready(function() {
$.ajax({
url:"https://example.xml.gz",
crossDomain: true,
success: function(data) {
console.log(data);
}});
});
I can see the compressed code of the gzipped file in my console returned from the AJAX call but don't know how to decompress it so I can use it in my project.
Could someone show me how to decompress a ZIP or GZIP file following an AJAX request.
I have tried the following solution from stackoverflow Is there a way to parse a zipped XML file with JQuery on the fly?
$(document).ready(function() {
$.ajax({
url:"https://example.xml.gz",
beforeSend: function (jqXHR) {
jqXHR.setRequestHeader('Accept-Encoding', 'gzip');
},
crossDomain: true,
success: function(data) {
console.log(data);
}});
});
This code returns an error in the console...
Attempt to set a forbidden header was denied: Accept-Encoding
I have also tried to set dataType: to "xml" but when I do this instead of seeing the compressed xml data in the console I see.
XML Parsing Error: not well-formed Location: http://192.168.0.11:3000/ Line Number 1, Column 1:

Interpreted as Document but transferred with MIME type application/pdf

In order to serve PDF-files to clients the following request is sent to a php file which encodes the pdf to base64 server side and sends it back to the client where it is added to an iframe:
var request = $.ajax({
url: "get-base64-pdf.php",
type: "POST",
data: {sessionid : sessionid},
dataType: "text"
});
request.done(function(msg){
$('#iframe').attr("src", "data:application/pdf;base64," + msg);
});
The script works but an error message from jquery (jquery-3.1.1.min.js:4) turns up in the console:
Resource interpreted as Document but transferred with MIME type application/pdf: "data:application/pdf;base64,
followed by the entire pdf in base64. I'm guessing this occurs because the data type is set to "text" but it will not work if changed to "application/pdf". Does anyone know if there is a way to either fix the issue or suppress the warning in the console?
EDIT
The php-script serves the base64 like so:
$b64Doc = chunk_split(base64_encode(file_get_contents("$Report")));
if($b64Doc){
header("Content-type: application/pdf");
echo $b64Doc;
} else {
echo -1;
}

Django ajaxuploader 400 badrequest error

Submitted.html
The JS is also surrounded by a document.ready function
var uploader = new qq.FileUploader({
action: "{% url 'QCOMLTE:imager' %}",
element: $('#file-uploader')[0],
multiple: true,
onComplete: function(id, fileName, responseJSON) {
if(responseJSON.success) {
alert("success!");
} else {
alert("upload failed!");
}
},
onAllComplete: function(uploads) {
// uploads is an array of maps
// the maps look like this: {file: FileObject, response: JSONServerResponse}
alert("All complete!");
},
params: {
'csrf_token': "{{ csrf_token }}",
'csrf_name': 'csrfmiddlewaretoken',
'csrf_xname': 'X-CSRFToken'
}
});
elsewhere in the html body
<div id="file-uploader">
<noscript>
<p>Please enable JavaScript to use file uploader.</p>
</noscript>
</div>
urls.py
urlpatterns = patterns('',
url(r"^Submitted/$", views.HybridDetailView.as_view(), name='Submitted'),
url(r'^(?P<object_type>\w+)/process/$', views.process, name='process'),
url(r'^(?P<object_type>\w+)/$', views.generic_view, name='generic'),
url("$^", views.head, name='head'),
url("uploader", views.upload, name= 'imager'),
)
views.py
#AjaxFileUploader
def upload(request):
response = {'files': []}
script_dir = os.path.dirname(__file__)
# Loop through our files in the files list uploaded
print('request',request)
print(request.FILES)
for item in request.FILES.getlist('files[]'):
file = UploadedFile(item)
with open(script_dir + '/Excel/' + file.name) as destination:
for chunk in file.chunks():
destination.write(chunk)
response['files'].append(file)
print('appended')
return HttpResponse(json.dumps(response), content_type='application/json')
also contains 'ajaxuploader' in the installed apps list
When I try to submit a file through the button it sends the post call but receives a 400 (BAD REQUEST) Error.
It's not even reaching the python from what I can tell, at least not the view code. It seems to form the request URL correctly
http://localhost:8000/QCOMLTE/uploader?qqfile=powered_by.png
And when you go to the URL it sends a message stating that post calls are only allowed.
This is similar to Default django-ajax-uploader with s3 backend gives MalformedXML error
Except that I'm not using any backends, just trying to grab the file/s and save them to a directory.
UPDATE 8/25/14:
Removed the decorator from the view. This results in the error not being sent. After printing the request it becomes evident that the file is being sent to the GET path instead of the FILE path. I don't know how to change this.
After finding this Need a minimal Django file upload example
I preceded to try and imitate it, to find that the FILE and POST requests were actually going through, unlike the ajax/jquery I was using. The JQuery was
$('#uploadform').submit(function (e){
console.log('submitting')
var data = new FormData($('#uploadform').get(0));
$.ajax({
type: 'POST',
url: "{% url 'QCOMLTE:imager' %}",
data: data,
success: function(data){console.log(data)},
error: function(data){console.log(data)},
cache: false,
processData: false,
contentType: false
});
e.preventDefault()
});
except the type was below URL.
I tried changing it to a $.post request and it was trying to post to the wrong URL then...
So I decided to change it back, and this time put type at the top of the ajax call. It then worked... and still does after much testing.

Dojo reading a json file from a local filesystem using dojo.xhrGet

I'm trying to read a file from a local filesystem. I do not have a server at my disposal and thus i'm trying to do it this way. Here is what I got so far;
function init(){
netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserWrite');
dojo.xhrGet(
{
url: "/json/coursedata.json",
handleAs:"json",
load: function (type, data, evt) {alert (data) },
//mimetype: "text/plain"
});
}
I'm getting this error from the firebug console;
Access to restricted URI denied" code: "1012
http://ajax.googleapis.com/ajax/libs/dojo/1.4/dojo/dojo.xd.js
Line 16
The solution was simple. Luckily accessing a file on your local file system, is not seen as a cross-domain request. So if the getCourse(course) is called by clicking on a button etc. The dojo.xhrGet retrieves the file course in the folder named json. The object data is the contents of the json file in the object format.
function getCourse(course)
{
dojo.xhrGet({
url: "json/" + course,
handleAs: "json",
handle: function(data,args){
populate_table(data);
}
});
}

Categories

Resources