選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

253 行
6.6 KiB

  1. # Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
  2. #
  3. # MIT License (MIT)
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a
  6. # copy of this software and associated documentation files (the "Software"),
  7. # to deal in the Software without restriction, including without limitation
  8. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  9. # and/or sell copies of the Software, and to permit persons to whom the
  10. # Software is furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  16. # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  17. # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18. # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  19. # CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
  20. # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. #
  22. import webnotes
  23. def upload():
  24. form = webnotes.form
  25. # get record details
  26. dt = form.getvalue('doctype')
  27. dn = form.getvalue('docname')
  28. at_id = form.getvalue('at_id')
  29. webnotes.response['type'] = 'iframe'
  30. if not webnotes.form['filedata'].filename:
  31. webnotes.response['result'] = """
  32. <script type='text/javascript'>
  33. window.parent.frms['%s'].attachments.dialog.hide();
  34. window.parent.msgprint("Please select a file!");
  35. </script>""" % dt
  36. return
  37. # save
  38. fid, fname = save_uploaded()
  39. # save it in the form
  40. updated = False
  41. if fid:
  42. updated = add_file_list(dt, dn, fname, fid)
  43. if fid and updated:
  44. # refesh the form!
  45. # with the new modified timestamp
  46. webnotes.response['result'] = """
  47. <script type='text/javascript'>
  48. window.parent.wn.widgets.form.file_upload_done('%(dt)s', '%(dn)s', '%(fid)s', '%(fname)s', '%(at_id)s', '%(mod)s');
  49. window.parent.frms['%(dt)s'].show_doc('%(dn)s');
  50. </script>
  51. """ % {
  52. 'dt': dt,
  53. 'dn': dn,
  54. 'fid': fid,
  55. 'fname': fname.replace("'", "\\'"),
  56. 'at_id': at_id,
  57. 'mod': webnotes.conn.get_value(dt, dn, 'modified')
  58. }
  59. # -------------------------------------------------------
  60. def add_file_list(dt, dn, fname, fid):
  61. """
  62. udpate file_list attribute of the record
  63. """
  64. try:
  65. # get the old file_list
  66. fl = webnotes.conn.get_value(dt, dn, 'file_list') or ''
  67. if fl:
  68. fl += '\n'
  69. # add new file id
  70. fl += fname + ',' + fid
  71. # save
  72. webnotes.conn.set_value(dt, dn, 'file_list', fl)
  73. return True
  74. except Exception, e:
  75. webnotes.response['result'] = """
  76. <script type='text/javascript'>
  77. window.parent.msgprint("Error while uploading: %s");
  78. </script>""" % str(e)
  79. def remove_all(dt, dn):
  80. """remove all files in a transaction"""
  81. file_list = webnotes.conn.get_value(dt, dn, 'file_list') or ''
  82. for afile in file_list.split('\n'):
  83. if afile:
  84. fname, fid = afile.split(',')
  85. remove_file(dt, dn, fid)
  86. def remove_file(dt, dn, fid):
  87. """Remove fid from the give file_list"""
  88. # get the old file_list
  89. fl = webnotes.conn.get_value(dt, dn, 'file_list') or ''
  90. new_fl = []
  91. fl = fl.split('\n')
  92. for f in fl:
  93. if f.split(',')[1]!=fid:
  94. new_fl.append(f)
  95. # delete
  96. delete_file(fid)
  97. # update the file_list
  98. webnotes.conn.set_value(dt, dn, 'file_list', '\n'.join(new_fl))
  99. # return the new timestamp
  100. return webnotes.conn.get_value(dt, dn, 'modified')
  101. def make_thumbnail(blob, size):
  102. from PIL import Image
  103. import cStringIO
  104. fobj = cStringIO.StringIO(blob)
  105. image = Image.open(fobj)
  106. image.thumbnail((tn,tn*2), Image.ANTIALIAS)
  107. outfile = cStringIO.StringIO()
  108. image.save(outfile, 'JPEG')
  109. outfile.seek(0)
  110. fcontent = outfile.read()
  111. return fcontent
  112. def save_uploaded(js_okay='window.parent.msgprint("File Upload Successful")', js_fail=''):
  113. import webnotes.utils
  114. webnotes.response['type'] = 'iframe'
  115. form, fid, fname = webnotes.form, None, None
  116. try:
  117. # has attachment?
  118. if 'filedata' in form:
  119. i = form['filedata']
  120. fname, content = i.filename, i.file.read()
  121. # get the file id
  122. fid = save_file(fname, content)
  123. # okay
  124. webnotes.response['result'] = """<script type='text/javascript'>%s</script>""" % js_okay
  125. else:
  126. webnotes.response['result'] = """<script type='text/javascript'>window.parent.msgprint("No file"); %s</script>""" % js_fail
  127. except Exception, e:
  128. webnotes.response['result'] = """<script type='text/javascript'>
  129. window.parent.msgprint("%s");
  130. window.parent.errprint("%s");
  131. %s</script>""" % (str(e), \
  132. webnotes.utils.getTraceback().replace('\n','<br>').replace('"', '\\"'), js_fail)
  133. return fid, fname
  134. # -------------------------------------------------------
  135. def save_file(fname, content, module=None):
  136. from webnotes.model.doc import Document
  137. # some browsers return the full path
  138. if '\\' in fname:
  139. fname = fname.split('\\')[-1]
  140. if '/' in fname:
  141. fname = fname.split('/')[-1]
  142. # generate the ID (?)
  143. f = Document('File Data')
  144. f.file_name = fname
  145. if module:
  146. f.module = module
  147. f.save(1)
  148. write_file(f.name, content)
  149. return f.name
  150. # -------------------------------------------------------
  151. def write_file(fid, content):
  152. import os, webnotes.defs
  153. # test size
  154. max_file_size = 1000000
  155. if hasattr(webnotes.defs, 'max_file_size'):
  156. max_file_size = webnotes.defs.max_file_size
  157. if len(content) > max_file_size:
  158. raise Exception, 'Maximum File Limit (%s MB) Crossed' % (int(max_file_size / 1000000))
  159. # no slashes
  160. fid = fid.replace('/','-')
  161. # save to a folder (not accessible to public)
  162. folder = webnotes.get_files_path()
  163. # create account folder (if not exists)
  164. webnotes.create_folder(folder)
  165. # write the file
  166. file = open(os.path.join(folder, fid),'w+')
  167. file.write(content)
  168. file.close()
  169. def get_file_system_name(fname):
  170. # get system name from File Data table
  171. return webnotes.conn.sql("""select name, file_name from `tabFile Data`
  172. where name=%s or file_name=%s""", (fname, fname))
  173. def delete_file(fid, verbose=0):
  174. """delete file from file system"""
  175. import os
  176. webnotes.conn.sql("delete from `tabFile Data` where name=%s", fid)
  177. path = os.path.join(webnotes.get_files_path(), fid.replace('/','-'))
  178. if os.path.exists(path):
  179. os.remove(path)
  180. # Get File
  181. # -------------------------------------------------------
  182. def get_file(fname):
  183. """deprecated"""
  184. f = get_file_system_name(fname)
  185. if f:
  186. file_id = f[0][0].replace('/','-')
  187. file_name = f[0][1]
  188. else:
  189. file_id = fname
  190. file_name = fname
  191. # read the file
  192. import os
  193. with open(os.path.join(webnotes.get_files_path(), file_id), 'r') as f:
  194. content = f.read()
  195. return [file_name, content]
  196. # -------------------------------------------------------