25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

271 satır
6.5 KiB

  1. def upload():
  2. import webnotes
  3. form = webnotes.form
  4. # get record details
  5. dt = form.getvalue('doctype')
  6. dn = form.getvalue('docname')
  7. at_id = form.getvalue('at_id')
  8. webnotes.response['type'] = 'iframe'
  9. if not webnotes.form['filedata'].filename:
  10. webnotes.response['result'] = """
  11. <script type='text/javascript'>
  12. window.parent.frms['%s'].attachments.dialog.hide();
  13. window.parent.msgprint("Please select a file!");
  14. </script>""" % dt
  15. return
  16. # save
  17. fid, fname = save_uploaded()
  18. # save it in the form
  19. updated = False
  20. if fid:
  21. updated = add_file_list(dt, dn, fname, fid)
  22. if fid and updated:
  23. # refesh the form!
  24. # with the new modified timestamp
  25. webnotes.response['result'] = """
  26. <script type='text/javascript'>
  27. window.parent.wn.widgets.form.file_upload_done('%(dt)s', '%(dn)s', '%(fid)s', '%(fname)s', '%(at_id)s', '%(mod)s');
  28. window.parent.frms['%(dt)s'].show_doc('%(dn)s');
  29. </script>
  30. """ % {
  31. 'dt': dt,
  32. 'dn': dn,
  33. 'fid': fid,
  34. 'fname': fname.replace("'", "\\'"),
  35. 'at_id': at_id,
  36. 'mod': webnotes.conn.get_value(dt, dn, 'modified')
  37. }
  38. # -------------------------------------------------------
  39. def add_file_list(dt, dn, fname, fid):
  40. """
  41. udpate file_list attribute of the record
  42. """
  43. import webnotes
  44. try:
  45. # get the old file_list
  46. fl = webnotes.conn.get_value(dt, dn, 'file_list') or ''
  47. if fl:
  48. fl += '\n'
  49. # add new file id
  50. fl += fname + ',' + fid
  51. # save
  52. webnotes.conn.set_value(dt, dn, 'file_list', fl)
  53. return True
  54. except Exception, e:
  55. webnotes.response['result'] = """
  56. <script type='text/javascript'>
  57. window.parent.msgprint("Error while uploading: %s");
  58. </script>""" % str(e)
  59. def remove_file_list(dt, dn, fid):
  60. """
  61. Remove fid from the give file_list
  62. """
  63. import webnotes
  64. # get the old file_list
  65. fl = webnotes.conn.get_value(dt, dn, 'file_list') or ''
  66. new_fl = []
  67. fl = fl.split('\n')
  68. for f in fl:
  69. if f.split(',')[1]!=fid:
  70. new_fl.append(f)
  71. # update the file_list
  72. webnotes.conn.set_value(dt, dn, 'file_list', '\n'.join(new_fl))
  73. # return the new timestamp
  74. return webnotes.conn.get_value(dt, dn, 'modified')
  75. def make_thumbnail(blob, size):
  76. from PIL import Image
  77. import cStringIO
  78. fobj = cStringIO.StringIO(blob)
  79. image = Image.open(fobj)
  80. image.thumbnail((tn,tn*2), Image.ANTIALIAS)
  81. outfile = cStringIO.StringIO()
  82. image.save(outfile, 'JPEG')
  83. outfile.seek(0)
  84. fcontent = outfile.read()
  85. return fcontent
  86. def save_uploaded(js_okay='window.parent.msgprint("File Upload Successful")', js_fail=''):
  87. import webnotes
  88. import webnotes.utils
  89. webnotes.response['type'] = 'iframe'
  90. form, fid, fname = webnotes.form, None, None
  91. try:
  92. # has attachment?
  93. if 'filedata' in form:
  94. i = form['filedata']
  95. fname, content = i.filename, i.file.read()
  96. # thumbnail
  97. if webnotes.form_dict.get('thumbnail'):
  98. try:
  99. content = make_thumbnail(content, int(form.get('thumbnail')))
  100. # change extension to jpg
  101. fname = '.'.join(fname.split('.')[:-1])+'.jpg'
  102. except Exception, e:
  103. pass
  104. # get the file id
  105. fid = save_file(fname, content)
  106. # okay
  107. webnotes.response['result'] = """<script type='text/javascript'>%s</script>""" % js_okay
  108. else:
  109. webnotes.response['result'] = """<script type='text/javascript'>window.parent.msgprint("No file"); %s</script>""" % js_fail
  110. except Exception, e:
  111. webnotes.response['result'] = """<script type='text/javascript'>window.parent.msgprint("%s"); window.parent.errprint("%s"); %s</script>""" % (str(e), webnotes.utils.getTraceback().replace('\n','<br>').replace('"', '\\"'), js_fail)
  112. return fid, fname
  113. # -------------------------------------------------------
  114. def save_file(fname, content, module=None):
  115. import webnotes
  116. from webnotes.model.doc import Document
  117. # some browsers return the full path
  118. if '\\' in fname:
  119. fname = fname.split('\\')[-1]
  120. if '/' in fname:
  121. fname = fname.split('/')[-1]
  122. # generate the ID (?)
  123. f = Document('File Data')
  124. f.file_name = fname
  125. if module:
  126. f.module = module
  127. f.save(1)
  128. write_file(f.name, content)
  129. return f.name
  130. # -------------------------------------------------------
  131. def write_file(fid, content):
  132. import webnotes, os, webnotes.defs
  133. # test size
  134. max_file_size = 1000000
  135. if hasattr(webnotes.defs, 'max_file_size'):
  136. max_file_size = webnotes.defs.max_file_size
  137. if len(content) > max_file_size:
  138. raise Exception, 'Maximum File Limit (%s MB) Crossed' % (int(max_file_size / 1000000))
  139. # no slashes
  140. fid = fid.replace('/','-')
  141. # save to a folder (not accessible to public)
  142. folder = webnotes.get_files_path()
  143. # create account folder (if not exists)
  144. webnotes.create_folder(folder)
  145. # write the file
  146. file = open(os.path.join(folder, fid),'w+')
  147. file.write(content)
  148. file.close()
  149. # -------------------------------------------------------
  150. def get_file_system_name(fname):
  151. # get system name from File Data table
  152. import webnotes
  153. return webnotes.conn.sql("select name, file_name from `tabFile Data` where name=%s or file_name=%s", (fname, fname))
  154. # -------------------------------------------------------
  155. def delete_file(fname, verbose=0):
  156. import webnotes, os
  157. for f in get_file_system_name(fname):
  158. webnotes.conn.sql("delete from `tabFile Data` where name=%s", f[0])
  159. # delete file
  160. file_id = f[0].replace('/','-')
  161. try:
  162. os.remove(os.path.join(webnotes.get_files_path(), file_id))
  163. except OSError, e:
  164. if e.args[0]!=2:
  165. raise e
  166. if verbose: webnotes.msgprint('File Deleted')
  167. # Get File
  168. # -------------------------------------------------------
  169. def get_file(fname):
  170. import webnotes
  171. in_fname = fname
  172. # from the "File" table
  173. if webnotes.conn.exists('File',fname):
  174. fname = webnotes.conn.sql("select file_list from tabFile where name=%s", fname)
  175. fname = fname and fname[0][0]
  176. fname = fname.split('\n')[0].split(',')[1]
  177. if get_file_system_name(fname):
  178. f = get_file_system_name(fname)[0]
  179. else:
  180. f = None
  181. # read the file
  182. import os
  183. file_id = f[0].replace('/','-')
  184. file = open(os.path.join(webnotes.get_files_path(), file_id), 'r')
  185. content = file.read()
  186. file.close()
  187. return [f[1], content]
  188. # Conversion Patch
  189. # -------------------------------------------------------
  190. def convert_to_files(verbose=0):
  191. import webnotes
  192. # nfiles
  193. fl = webnotes.conn.sql("select name from `tabFile Data`")
  194. for f in fl:
  195. # get the blob
  196. blob = webnotes.conn.sql("select blob_content from `tabFile Data` where name=%s", f[0])[0][0]
  197. if blob:
  198. if hasattr(blob, 'tostring'):
  199. blob = blob.tostring()
  200. # write the file
  201. write_file(f[0], blob)
  202. if verbose:
  203. webnotes.msgprint('%s updated' % f[0])
  204. # -------------------------------------------------------