blob-upload-3.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from flask import Flask
  2. from flask import jsonify
  3. from flask import request
  4. from werkzeug import secure_filename
  5. from azure.storage.blob import BlockBlobService
  6. import os
  7. app = Flask(__name__, static_folder='static', static_url_path='')
  8. app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
  9. app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024 # 1 Mb limit
  10. app.config['AZURE_STORAGE_ACCOUNT'] = "flasktest"
  11. app.config['AZURE_STORAGE_CONTAINER'] = "doc"
  12. app.config['AZURE_STORAGE_KEY'] = os.environ['AZURE_STORAGE_KEY']
  13. try:
  14. os.environ['FLASK_DEBUG']
  15. app.debug = True
  16. except KeyError:
  17. app.debug = False
  18. def allowed_file(filename):
  19. return '.' in filename and \
  20. filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
  21. @app.route('/')
  22. def root():
  23. return app.send_static_file('index.html')
  24. # basedir = os.path.abspath(os.path.dirname(__file__))
  25. @app.route('/uploadajax', methods=['POST'])
  26. def upldfile():
  27. if request.method == 'POST':
  28. file = request.files['file']
  29. if file and allowed_file(file.filename):
  30. filename = secure_filename(file.filename)
  31. app.logger.info('FileName: ' + filename)
  32. block_blob_service = BlockBlobService(account_name=app.config['AZURE_STORAGE_ACCOUNT'], account_key=app.config['AZURE_STORAGE_KEY'])
  33. block_blob_service.create_blob_from_bytes(
  34. 'doc',
  35. filename,
  36. file.read())
  37. # updir = os.path.join(basedir, 'upload/')
  38. # file.save(os.path.join(updir, filename))
  39. # file_size = os.path.getsize(os.path.join(updir, filename))
  40. return jsonify(name=filename, url='https://'+app.config['AZURE_STORAGE_ACCOUNT']+'.blob.core.windows.net/' \
  41. +app.config['AZURE_STORAGE_CONTAINER']+'/'+filename)
  42. if __name__ == '__main__':
  43. app.run()