How to save an image via JavaScript - javascript

I want to download a image file (jpeg image) to the user files system when user selects a photo and clicks a button. So far I searched and found this link and also this
I saw in one blog that downloadify when used with jszip can enable this feature but it didn't specify any farther on this. Does any one know how to download the images. I have the links to the images and i just want the user to download it on his system rather than again query the server.
Can anyone provide me with an example please.

Use the HTML5 download attribute.
As a choice you can set filename as an attribute value.
<a href="/images/image-name.jpg" download="new-image-name.jpg">

You can load the image in an canvas element get the data url of the canvas and open a new window with the data url as source. Take a look at this example: https://gist.github.com/1875132

Finally I did it. For anyone who may need this in the future here is how I did it using jquery
jQuery.ajax({
url: 'http://localhost:8080/yourwebsite/servlet?img=' + document.getElementById(id).alt,
//data: myData,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
// success: function() { alert("Success"); },
// error: function() { alert('Failed!'); },
// beforeSend: setHeader
});
this I had to do come across the problem of cross domain http requests which are usually blocked by most websites unless you follow some lengthy process. So, I made it simpler and called a get method in my servlet and passed it the url of the image from which it downloaded the image.This is much easier to do and even easier then this if you are on the same domain but that didn't meet my requirements and this code worked for me :)

Related

How to download multiple HTML pages to dropbox with apify using jquery ajax

I'm using Apify to crawl about a hundred pages, and I wish to download the HTML files of all the pages I visit into a dropbox folder. How do I specify this in my jQuery Ajax code?
Sorry in advance, I am quite new to Javascript and everything web-related.
I've tried to follow these tutorials already: https://forum.apify.com/t/data-download-from-within-crawler/48 and https://www.dropbox.com/developers/documentation/http/documentation#files-save_url, however, I am only able to download the HTML file of the second page I visit. I know that my crawler works perfectly fine and visits all the sites it needs to, as I am getting the results I need from these pages, so the problem seems to be that I am not specifying that I want to download all the HTML files. How do I do this?
(In my actual code I have written in the correct Oath-token, I just don't want it to be available online for everyone to see)
var html = $('html').html();
var url = "https://content.dropboxapi.com/2/files/upload";
$.ajax({
url: url,
contentType: "application/octet-stream",
headers: {
"Authorization": 'Bearer ' + 'My Oath-token',
"Dropbox-API-Arg": "{\"mode\":\"add\",\"path\":\"/a.txt\"}",
},
type: 'POST',
data: html,
autoRename: true,
max_results: 1000
});
What I am getting out of this is one file saved as a.txt in my dropbox, which is what I wanted, only that this file only includes one HTML file, not a file including all the files my crawler had visited.
This code is the first thing my crawler meets for every new page it visits.

Append formdata for multiple file upload [duplicate]

I need to upload files using ajax which has to be supported in IE9. I was using FormData as mentioned here. My code looks like this:
var files = new FormData();
JQuery.each($('#file')[0].files, function (i, file) {
files.append('file', file);
});
$.ajax({
type: "POST",
url: '/url',
cache: false,
contentType: false,
processData: false,
data: files,
...
});
This works fine in Safari and Firefox, but fails in IE9 as the FormData is not supported in IE9. I tried sending just as a file by setting:
data: $('#file')[0].files[0]
contentType: 'multipart/form-data'
This fails as the data is sent in url-encoded form and is cannot be parsed at the java side. Any help or pointer on how to solve this will be greatly appreciated. I need something that works across all browsers.
EDIT: I do not need any upload progress bar as the files are usually small. I do not need to upload multiple files. I just need a single file upload.
Unfortunately you cannot use Ajax (XMLHttpRequest in other words) for sending files, but you can implement a similar behavior using the <iframe/> with a <form method="post" enctype="multipart/form-data"/> that contains an <input type="file"/> which sends a user chosen file using the "natural" way. You can use javascript to call the form.submit() then poll that <iframe/> from parent document to check whether the file upload process is done.
jQuery has a lot of cool plugins for getting this job done, there is my favorite one, for example.

Ajax put to add XML entries into XML file

I am trying to add some emails taken from an inputbox into a .txt file present on my webserver. Here is the code :
email = document.getElementById("mail").value;
$.ajax({
url: 'maillist.txt',
datatype: 'text',
type: 'PUT',
data: email + '; ',
success: function(data) {
alert('Should have work yay!');
}
});
but that doesn't work on any browser. :(
I have tried using javascript classic methods but it was a no go as well...
I would need either a PUT or POST method, either jQuery or JS, to be able to do this on internet explorer 8 and up as well as firefox and chrome. Emails should appear in the text file as
email1#cooldomain.com; email2#cooldomain.com; .....
Just so it works with our in-house VBA Macro. :)
Also, could there be a method for dropping data into XML files (aka create a new XML entry with form data)? And also, is it possible to upload a file from client side to server side using jQuery? Because i would need users to fill up forms and drop their data into an XML file, and link up a file they choose with that. That way they could add stuff into the XML themselves and they would show up brand new into the webpage.
Kindoff "reddit" or "4chan" like if you know the references.
Thanks for your time, really appreciated!
You can't post from a browser to a text file on the server side. You need to have some sort of code on the server side that will receive the HTTP PUT, and persist the data to a file local to the server.

trying to make call for external style sheet from amazon s3

The idea is to make a widget or "chunk" of a website that can be inserted onto someone else's webpage by just adding a script tag to my javascript file located on amazon s3 and a div that I will insert content into. I also uploaded the css and HTML files to amazon but when I try to make a call to them in the javascript I get errors. I tried variations of the code below and got various errors, most recently 403, forbidden. I made the files public on amazon too. Please let me know if you have a suggestion/solution!
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "https://s3.amazonaws.com/lawkickstas/lawkick.css"
});
css_link.appendTo('head');
var jsonp_url = "https://s3.amazonaws.com/lawkickstas/lawkick_html.js";
$.ajax({
url: jsonp_url,
dataType: 'jsonp',
success: function(dataWeGotViaJsonp){
console.log(dataWeGotViaJsonp);
}
});
Just a guess from the limited info you have on the error. There is specific setting required on S3 if the access has to be from another domain.
You might want to check this. Enabling Cross-Origin Resource Sharing - Amazon Simple Storage Service

Make a JSON POST request to server, receive a binary response (an Excel file), how to download it?

I'm trying to to make a POST call to server that sent JSON data to it. The server takes the JSON data, do some processing, then send back an Excel .xlsx as the response. I want the browser to open the "Save file as" dialog for the user to save. I have been looking for a clean solution to do this. But one possible solution in this question JavaScript/jQuery to download file via POST with JSON data suggest to save the Excel file on the server then send back a URL link, then open an iframe for user to download. This is a no-go for me, as the users can create thousands Excel files on the server and the server has limited saving spaces. I want the solution to be on-the-fly. Another solution I have seen suggested to convert data into form, then using form submit. Again this is a no-go, since my data is in the range of hundreds if not thousands of Excel rows.
My jQuery POST call:
$.ajax({
type: 'POST',
url: '/server/path',
data: JSON.stringify(dataSent),
processData: false,
success: function(data, textStatus, jqXHR) {
},
error: function(result, status, err) {
},
contentType: 'application/json',
dataType: 'application/vnd.ms-excel'
});
In the backend I set this :
Response.header("Content-Type", "application/vnd.ms-excel")
Response.header("Content-Disposition", "attachment; filename=\"export.xlsx\"")
What the best way to force the browser to open "Save file as ..." dialog ?
Thanks,
I'm not sure there's a way to recieve binary data via JS and then initiate the download.
If I were tasked with this, I would change the method to a GET and generate the file (as a stream) and return it with the appropriate headers (Content-Disposition, Content-Length, Content-Type)
I figure out a way around this. Instead of making a POST call to force the browser to open the save dialog, I will make a POST call to generate the file, then temporary store the file on the server, return the filename . Then use a GET call for this file with "Content-Disposition: attachment; filename=filename1". The GET call with that header will force the browser to open the "Save this file" dialog, always.
This is actually very easy with Blob URLs.
First, download the file. I'll use fetch with async/await in TypeScript (you can always use promise chains instead of async/await and/or XHR instead of fetch):
(async () => {
let response = await fetch("/post/path", {
body: JSON.stringify(data), // must match 'Content-Type' header
headers: {
'content-type': 'application/json'
},
method: 'POST',
});
let blob = await response.blob();
let filename = "file.txt";
saveBlobAsFile(filename, blob); // This function is defined below
})();
Now that you have a blob, you can pass it to a function to download it by creating a Blob URL and a hidden link:
/**
* Downloads a blob as a file.
*
* TODO: Support iOS Safari, which doesn't support the "download" attribute.
*
* #param name The name of the downloaded file
* #param blob The blob to download
*/
export function saveBlobAsFile(name: string, blob: Blob) {
// IE10 & IE11 Support, since they don't support the "download"
// attribute on anchor tags.
if (navigator.msSaveBlob) {
navigator.msSaveBlob(blob, name);
return;
}
// Create the URL and hidden anchor tag
let $hiddenAnchorTag = $('<a style="display: none;"/>');
let url = URL.createObjectURL(blob);
// Set the attributes for the download
$hiddenAnchorTag.attr('href', url);
$hiddenAnchorTag.attr('download', name);
// Insert the link and click to download
$(document.body).append($hiddenAnchorTag);
$hiddenAnchorTag[0].click();
// Clean up after ourselves
$hiddenAnchorTag.remove();
URL.revokeObjectURL(url);
}
Other Notes
The fetch response object contains the headers, so you can parse the Content-Disposition to get the filename intended by the server. I found a couple good Regexes around the web that work pretty well for this. Mileage may vary, but I recommend making a function for this and bounding it with some nice unit tests.
This works a lot better than trying to set the current location to the location of the file, because it allows you to include more details in the POST, including API keys or something similar for security, plus it allows you to handle errors/exceptions cleanly, and know when the operation is complete (such as warning on trying to navigate away from the page that the user is still waiting on a download).
Blobs even support slicing in data, so you could extend this to download large files by fetching the individual slices (yay Content-Range!) and assembling them into a single Blob, and downloading the final blob, all while giving the user a nice loading progress indicator!
You can use Blob URLs just like any other URLs. They point to the resource, so you could pass that URL to img tags, other libraries that ask for URLs, src tags, etc.
#phamductri Serving up temporary files on the server can be very dangerous! If you need to use that pattern, you'll want to abstract the filename using a table or lookup, so the user doesn't have control over the actual filenames or paths (use UUIDs in a specified directory), and make sure users can only download the files they generated. Just a few of things you need to ensure are as follows (this is not a comprehensive list):
Users can't specify an arbitrary path to save to
They could save over your database configuration file, etc.
Users can't specify an arbitrary path to read to
They could read your database configuration file, etc.
File names can't conflict.
User A generates a file with the name "accounts_to_pay.csv". User B generates a file at the same time with the same name (either maliciously or accidentally), and now User A is paying whoever User B wants them to.

Categories