如何将InMemoryUploadedFile对象复制到磁盘

51 投票
6 回答
65036 浏览
提问于 2025-04-16 04:05

我正在尝试处理一个通过表单发送的文件,并在保存之前对它进行一些操作。所以我需要在临时目录中创建这个文件的副本,但我不知道该怎么做。Shutil的函数无法复制这个文件,因为我没有找到它的路径。那么有没有其他方法可以完成这个操作呢?

我的代码:

    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)

这段代码引发了:

异常类型:IOError 在 /
异常信息:(2, '没有这样的文件或目录')

调试信息:

#  (..)\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'

6 个回答

8

这里有另一种方法可以使用Python的 mkstemp 来实现:

### get the inmemory file
data = request.FILES.get('file') # get the file from the curl

### write the data to a temp file
tup = tempfile.mkstemp() # make a tmp file
f = os.fdopen(tup[0], 'w') # open the tmp file for writing
f.write(data.read()) # write the tmp file
f.close()

### return the path of the file
filepath = tup[1] # get the filepath
return filepath
31

正如@Sławomir Lenart提到的,当你上传大文件时,不想让系统内存被一个data.read()占满。

来自Django文档

使用UploadedFile.chunks()来循环处理,而不是用read(),可以确保大文件不会让你的系统内存崩溃。

from django.core.files.storage import default_storage

filename = "whatever.xyz" # received file name
file_obj = request.data['file']

with default_storage.open('tmp/'+filename, 'wb+') as destination:
    for chunk in file_obj.chunks():
        destination.write(chunk)

这将把文件保存在MEDIA_ROOT/tmp/目录下,除非你另有指示,你的default_storage会这样做。

70

这个问题跟你提的很像,可能会对你有帮助。

import os
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.conf import settings

data = request.FILES['image'] # or self.files['image'] in your form

path = default_storage.save('tmp/somename.mp3', ContentFile(data.read()))
tmp_file = os.path.join(settings.MEDIA_ROOT, path)

撰写回答