如何将InMemoryUploadedFile对象复制到dis

2024-10-06 11:25:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图捕获一个与表单一起发送的文件,并在保存之前对其执行一些操作。所以我需要在temp目录中创建这个文件的副本,但我不知道如何访问它。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)

由此引发:

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

以及调试:

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

Tags: 文件pathimagesrcnoneifosmyfile
3条回答

最好的做法是编写一个自定义上载处理程序。请参阅docs。如果添加“文件完整”处理程序,则可以访问文件的内容,而不必考虑是否有内存文件或临时路径文件。您也可以使用“receive_data_chunck”方法并在其中写入副本。

问候

This是类似的问题,可能会有帮助。

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)

@ups所述,在上载大型文件时,您不希望使用data.read()阻塞系统内存。

来自Django docs

Looping over UploadedFile.chunks() instead of using read() ensures that large files don't overwhelm your system's memory

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/保存文件,除非另有说明。

相关问题 更多 >