Jquery/Javascript upload and download a file without a backend

走远了吗. 提交于 2019-12-12 13:20:02

问题


Is is possible to download and upload a file in a JavaScript function without a backend server? I need to export and import a XML made by a JavaScript function. I would like to create button "Save xml" to save a file but I don't know if it is possible. By other hand I wish to upload a XML file directly to JavaScript. If it is not possible I will use a backend server just like a proxy.


回答1:


I think you could look in to the HTML5 file api. Based on what you said all file should never leave the domain of the browser or the webapp. I believe this could cause some problems the user would be forced to use the same browser to access files. Also HTML5 standards have still not been fully implemented by all major browsers, that would be another risk. However if you want to go down that route I provided some resources that may help. I would recommend hosting the files, not my project I don't know your use cases.

http://www.html5rocks.com/en/tutorials/file/dndfiles/

http://updates.html5rocks.com/2011/08/Saving-generated-files-on-the-client-side

http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download

http://eligrey.com/demos/FileSaver.js/




回答2:


I am not sure If I understand this well but it seems like you want to submit data to a remote client and also receive data.

Receiving and saving XML Since its XML you can use an ajax post/get* and parse your xml data from the receiving end and you will want to have an object that holds your XML data in case you want to save.

var myXMLContainer = "";
$.ajax({
    type: "Get",
    datatype: "xml",
    url: "your url sending xml data",
    data: xmlData,
    success: function (result) {
        myXMLContainer = $.parseXML(result);
        $("#myHiddenDiv").text(myXMLContainer);
    }
});

Saving your data. Since JavaScript doesn't have access to writing files as this would be a huge security risk to say the least. You would set your data to a hidden div and set it to btoa to save your data.

function saveData(){
   btoa($("#myHiddenDiv").text());
}

I hope this is clear enough to get by....



来源:https://stackoverflow.com/questions/21230012/jquery-javascript-upload-and-download-a-file-without-a-backend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!