Alex Rivera | Logout

How do I copy an InMemoryUploadedFile object to disk?

Asked 2010-09-13T16:37:24.880
52

I am trying to catch a file sent through a form and perform operations on it before saving so I need to create a copy in the temp directory, but I don't know how to reach it. Shutil's functions fail to copy this file since there is no path to it. How can I do this?

My code:

image = form.cleaned_data['image']
temp = os.path.join(settings.PROJECT_PATH, 'tmp')
sourceFile = image.name # without .name here it wasn't working either
import shutil
shutil.copy(sourceFile, temp)

Which raises:

Exception Type: IOError at /
Exception Value: (2, 'No such file or directory')

Debug:

#  (..)\views.py in function

  67. sourceFile = image.name
  68. import shutil
  69. shutil.copy2(sourceFile, temp) ...

# (..)\Python26\lib\shutil.py in copy2

  92. """Copy data and all stat info ("cp -p src dst").
  93.
  94. The destination may be a directory.
  95.
  96. """
  97. if os.path.isdir(dst):
  98. dst = os.path.join(dst, os.path.basename(src))
  99. copyfile(src, dst) ...
 100. copystat(src, dst)
 101.

▼ Local vars
Variable    Value
dst
u'(..)\\tmp\\myfile.JPG'
src
u'myfile.JPG'
# (..)\Python26\lib\shutil.py in copyfile

  45. """Copy data from src to dst"""
  46. if _samefile(src, dst):
  47. raise Error, "`%s` and `%s` are the same file" % (src, dst)
  48.
  49. fsrc = None
  50. fdst = None
  51. try:
  52. fsrc = open(src, 'rb') ...
  53. fdst = open(dst, 'wb')
  54. copyfileobj(fsrc, fdst)
  55. finally:
  56. if fdst:
  57. fdst.close()
  58. if fsrc:

▼ Local vars
Variable    Value
dst
u'(..)\\tmp\\myfile.JPG'
fdst
None
fsrc
None
src
u'myfile.JPG'
Edit
Report

1 Answer

5

Write a custom upload handler. With a file_complete handler you can access the file's content regardless of having a memory file or a temp path file. You can also use receive_data_chunk() and write your copy within it.

answered 2010-09-13T16:50:30.673

Your Answer