[Django]-With JS, jQuery, how do I save an AJAX response to a (text) file?

1đź‘Ť

From the browser’s point of view, it doesn’t matter if the file exists or not, it’s just a resource on a server that it’s requesting. I think you’re going to need to do some version of “Just set the window location to the file”. If you set the content type in the header to something that the browser doesn’t recognize, I believe it will ask the user if they want to save it.

👤morgancodes

1đź‘Ť

As others mentioned, you can’t do it only with JavaScript.

IMO the best option would be the Flash 10+ FileReference API.

There are some good JavaScript wrapper libraries like Downloadify that provide a JavaScript API to access those methods.

Give a look to this demo.

0đź‘Ť

This isn’t something JavaScript (and therefore jQuery or anything other JS framework) is allowed to do, for security reasons. You may be able to do what you want to flash or another route, but not JavaScript. Bear in mind Flash has it’s own slew of security restrictions for this as well.

(Yes, IE can do this via an ActiveX object, but I’m not counting that as a “solution” here)

👤Nick Craver

0đź‘Ť

Basically, no. Javascript cant save anything to the local machine due to security restrictions. Your best bet may be to have a signed applet that the user can trust to write the file, or put it in a textarea that they can then easily copy and paste into a new file.

👤gub

0đź‘Ť

Could you not use the PHP rename() function for this, instead of just Javascript? Call to a PHP file and pass the name of the file you want to copy along with where as parameters?

👤d2burke

-1đź‘Ť

I have the same problem. You can try this

<button id="Save">Save</button>
<img src="MakeThumbnail.ashx?Image=1.jpg" id="imgCrop">

$("#Save").click(function (e) {
    url = $("#imgCrop").attr("src")+"&Action=Save"
    e.preventDefault();  //stop the browser from following
    window.location.href = url;
});
👤evgeny

Leave a comment