2011-07-09 78 views
3

我正在做一些文件驗證,並且想在將它保存在某個可以執行的地方之前,將它加載到'/ tmp'目錄中的同時將一個UploadedFile加載到外部庫中。 Django的執行以下操作:如何獲取Django中UploadedFile的臨時名稱?

Django will write the uploaded file to a temporary file stored in your system's temporary directory. On a Unix-like platform this means you can expect Django to generate a file called something like /tmp/tmpzfp6I6.upload.

它IHE「tmpzfp616.upload」,我希望能夠得到我的手UploadedFile.name給我。‘’而file.name給我的文件的正確名稱「example.mp3」。

隨着我使用,我需要的臨時文件的文件路徑傳遞到庫庫,而不是文件本身,因此,需要的字符串。

任何想法?

在此先感謝。

編輯:這裏是我的代碼:

from django.core.files.uploadedfile import UploadedFile 

    class SongForm(forms.ModelForm): 
     def clean_audio_file(self): 
      file = self.cleaned_data.get('audio_file',False) 
      if file: 
       [...] 

       if file._size > 2.5*1024*1024: 
        try: 
         #The following two lines are where I'm having trouble, MP3 takes the path to file as input. 
         path = UploadedFile.temporary_file_path 
         audio = MP3('%s' %path) 
        except HeaderNotFoundError: 
         raise forms.ValidationError("Cannot read file") 

      else: 
       raise forms.ValidationError("Couldn't read uploaded file") 
      return file 

使用 「UploadedFile的」 我得到一個AttributeError 「類型的對象 'UploadedFile的' 有沒有屬性 'temporary_file_path'」。如果我改用file.temporary_file_path(只是扔飛鏢在這裏黑暗中)我得到一個IO錯誤:

[Errno 2] No such file or directory: 'bound method TemporaryUploadedFile.temporary_file_path of >'

我意識到temporary_file_path是我要找的解決方案,我只是無法弄清楚如何使用它和文檔或谷歌似乎都沒有太多的幫助,在這個特殊的情況下。

回答

5

UploadedFile.temporary_file_path

Only files uploaded onto disk will have this method; it returns the full path to the temporary uploaded file.

+0

我看到的文檔,但我不能讓它正常工作...我會添加上面我的代碼。謝謝 –

+1

您需要訪問'UploadedFile'實例上的temporary_file_path方法。如果你的實例是名字文件,你可以像這樣訪問路徑:'file.temporary_file_path()'。 – rzetterberg

+0

謝謝@Ancide! –

相關問題