2017-09-27 81 views
0

我想使用Rest將文件上傳到DJango Python API。但我注意到文件被修改了。具體來說就是添加內容處置。我還沒有找到一個很好的方法來消除這一點。問題是我試圖上傳需要解壓縮的tar,但修改後的內容會阻止解壓縮文件。Django Python文件上傳如何保留原始文件

我使用的是其他頁面上此文件分析器: 從rest_framework.parsers導入FileUploadParser

下面的代碼似乎得到的文件對我來說在APIView的POST方法

file_obj = request.FILES['file'] 
 
scanfile.file.save(file_obj.name, file_obj)

其中scanfile是帶有文件字段的模型。 該文件被保存的內容是這樣的:

--b3c91a6c13e34fd5a1e253b1a72d63b3 
 
Content-Disposition: form-data; name="file"; filename="sometar.tgz" 
 
My tar file contents here..... 
 
--b3c91a6c13e34fd5a1e253b1a72d63b3

我的客戶是這樣的:

filename = "sometar.tgz" 
 
exclusion = "../../exclusionlist.txt" 
 
headers = {'Content-Type': 'multipart/form-data;’, 
 
      'Authorization': 'JWT %s' % token, 
 
      } 
 
url = "http://localhost:%s/api/scan/Project/%s/" % (port, filename) 
 
#files = {'file': open(filename, 'rb'), 'exclusion_file': open(exclusion, 'rb')} # also tried this way but it just put the info in the same file and I see the headers in the file 
 
files = [('file', open(filename, 'rb')), ('file', open(exclusion, 'rb'))] 
 
x = requests.post(url, files=files, headers=headers)

所以我的問題是我怎麼刪除來自保存文件的內容處置信息,所以我可以贊成perly解壓文件?

回答

0

request.FILES['file']是一個UploadedFile對象。你可以通過request.FILES['file'].name得到它的名字,並得到request.FILES['file'].read()的內容。

你應該小心read()和大文件:

Read the entire uploaded data from the file. Be careful with this method: if the uploaded file is huge it can overwhelm your system if you try to read it into memory. You’ll probably want to use chunks() instead; see below.

https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest.FILES https://docs.djangoproject.com/en/1.11/ref/files/uploads/#django.core.files.uploadedfile.UploadedFile

+0

我試圖與.read()和.chunks(),以及和任何一種方式的文件仍然有內容處置標籤。 – Mark

+0

我有一個解決辦法,但它涉及到手動刪除行:tempfile.NamedTemporaryFile()作爲tmp: lines = file_obj.readlines() tmp.writelines(lines [3:-1]) tmp.seek(0) – Mark

+0

我試過再讀()並得到一個錯誤。所以這就是我沒有使用它的原因。文件「/utils.py」,第16行,在 read = property(lambda self:self.file.read) AttributeError:'str'object has no attribute'read'code is now scanfile.file.save(file_obj .name,file_obj.read()),但它似乎是一個不是UploadedFile的字符串。 scanfile仍然是file_obj = request.FILES ['file'] – Mark

相關問題