DJango Python File Upload如何保存原始文件 [英] DJango Python File Upload how to preserve orginal file
问题描述
我正在尝试使用Rest将文件上传到DJango Python API。但是我注意到文件被修改了。具体而言,向其添加了内容配置。我还没有找到删除此文件的好方法。问题是我试图上传需要解压缩的tar,但是修改后的内容阻止了文件的解压缩。
I am trying to upload a file using Rest to a DJango Python API. But I noticed the file gets modified. Specifically a content-disposition is added to it. I haven't found a good way to remove this. The problem is I am trying to upload a tar that needs to be unzipped, but the modified content prevents unzipping the file.
我在休息时使用此文件解析器页面:rest_framework.parsers中的
导入FileUploadParser
I’m using this file parser on a rest page: from rest_framework.parsers import FileUploadParser
以下代码似乎在APIView的post方法中为我获取了文件
The following code seems to get the file for me in the post method of an APIView
file_obj = request.FILES['file']
scanfile.file.save(file_obj.name, file_obj)
其中scanfile是带有文件字段的模型。
使用以下内容保存文件:
Where scanfile is a model with a file field. The file gets saved with contents like this:
--b3c91a6c13e34fd5a1e253b1a72d63b3
Content-Disposition: form-data; name="file"; filename="sometar.tgz"
My tar file contents here.....
--b3c91a6c13e34fd5a1e253b1a72d63b3
我的客户看起来像这样:
My client looks like this:
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)
所以我的问题是如何从已保存的文件中删除该内容处置信息,以便正确解压缩
So my question is how do I remove that content-disposition info from the saved file so I can properly unzip the file?
推荐答案
request.FILES ['file']
是 UploadedFile 对象。您可以通过 request.FILES ['file']。name
获得其名称,并通过 request.FILES ['file']获得其内容。 read()
。
request.FILES['file']
is an UploadedFile object. You can get its name with request.FILES['file'].name
and get just the content with request.FILES['file'].read()
.
您应该谨慎使用 read()
和大文件:
You should be careful with read()
and big files:
从文件中读取全部上传的数据。请谨慎使用此
方法:如果
尝试将其读入内存,则如果上载的文件很大,则可能使您的系统不堪重负。您可能要改用chunks()
;
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/zh-CN/1.11/ref/request-response/#django.http.HttpRequest.FILES
https:// docs.djangoproject.com/en/1.11/ref/files/uploads/#django.core.files.uploadedfile.UploadedFile
这篇关于DJango Python File Upload如何保存原始文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!