No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

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