2017-09-27 23 views
0

私はDJango Python APIにRestを使ってファイルをアップロードしようとしています。しかし、私はファイルが変更されていることに気づいた。具体的にはコンテンツの配置が追加されます。私はこれを削除するための良い方法を発見していない。問題は、解凍する必要があるタールをアップロードしようとしていますが、変更されたコンテンツがファイルの解凍を妨げていることです。DJango Pythonファイル元のファイルを保存する方法をアップロード

私は残りのページにこのファイルパーサーを使用しています:rest_framework.parsersから は、次のコードは、APIView

file_obj = request.FILES['file'] 
 
scanfile.file.save(file_obj.name, file_obj)
のPOSTメソッドで私のためにファイルを取得するようだFileUploadParser

をインポート

ここで、scanfileはファイルフィールドを持つモデルです。 ファイルは、このような内容で保存されます:だから私の質問は、私は削除しない方法です

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)

:私のクライアントは、このようになります

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

保存できるファイルからのコンテンツの処分情報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()だけでなく、ファイルがまだ持っているいずれかの方法content-dispositionタグが含まれています。 – Mark

+0

私は回避策がありますが、手動で行を削除する必要があります。tempfile.NamedTemporaryFile()をtmp: lines = file_obj.readlines() tmp.writelines(行[3:-1]) tmp.seek(0) – Mark

+0

私はread()をもう一度試してエラーが発生しました。だから私はそれを使わなかったのです。ファイル "/utils.py"、16行目、 read =プロパティ(lambda self:self.file.read) AttributeError: 'str'オブジェクトには属性がありません 'read'コードは現在scanfile.file.save(file_obj .name、file_obj.read())が、アップロードされたファイルではない文字列のように見えます。 scanfileはまだですfile_obj = request.FILES ['file'] – Mark

関連する問題