1

I've got a linux machine with a web server, and I use google BLockly to generate python code. It generates it correctly, and I use alert(code) to show the code. How can I save it into a file located in the same web server?

function showCode() {
  // Generate Python code and display it.
  var code = Blockly.Python.workspaceToCode(workspace);
  alert(code);
}

1 Answers1

0

I didn't understand the context fully, I think you are generating the code at client side and you want to save it. If you want to save it in client side (file save option from browser), use the following library

https://github.com/eligrey/FileSaver.js

if you want to save it at server side, post the data to the server from your javascript itself and write the contents to a file in the server.

lets use jquery to post data. assume your code is there in the variable 'code'

    $.post("/savecode",
    {
      data: code
    },
    function(data,status){
        alert("Data: " + data + "\nStatus: " + status);
    });

This will post the data to the uri 'savecode'

i think, you created a static html page with some javascript inside and serving it from /var/ww/html/ folder of a apache or https server. this won't work, you need to serve it from a web application. i am choosing python flask here which is pretty simple.

to receive the data and store in a server, assuming that your static page is home.html and is there in templates folder

from flask import Flask, render_template, request
from werkzeug import secure_filename
app = Flask(__name__)


# Sending the home page when browsing /home
@app.route('/home')
def home():
   return render_template('home.html')


# Saving the code posted by the javascript app
@app.route('/savecode', methods=['POST'])
def savecode():      
    f = request.files['file']
    f.save(secure_filename(f.filename))
    return 'file saved successfully'

if __name__ == '__main__':
   app.run()

for more info, look flask docs : http://flask.pocoo.org/

You can create the server program in any language/framework that you are comfortable with.

Jomin
  • 113
  • 2
  • 8
  • I want to save it at server side, but i'm only learning Javascript and I'm not able to write the file – Davide Pacchiarotti Jul 19 '17 at 20:41
  • The logic of writing file sits at server side and depends on what framework that you have used, the logic of sending the data sits at client side and you can do it via simple javascript or jquery. – Jomin Jul 19 '17 at 21:18
  • file-save saves file in text format. How can i save file in .py format on client side? – Arbaz Sheikh Sep 29 '20 at 04:22