在django服务器上,我处理从python脚本发送的上传zip文件。但是我得到了file.content_type的“”(空字符串)。我做错了什么?
@csrf_exempt
def Import( request ):
if request.method != 'POST':
return HttpResponseNotAllowed('Only POST here')
if not request.FILES or not request.FILES.get( u'file' ):
return HttpResponse('Must upload a file')
file = request.FILES[u'file']
if file.content_type == 'application/zip':
unzipped_dir = unzip_file( file )
uid = create_project( unzipped_dir )
shutil.rmtree( unzipped_dir )
py_ob = { }
py_ob['success'] = uid is not None
if uid is not None:
py_ob['id'] = uid
json_ob = simplejson.dumps(py_ob)
return HttpResponse( json_ob, mimetype="application/json" )
else:
return HttpResponseNotAllowed( 'Only POST zip files here' )
这是发送zip文件的脚本:
import sys
import os
import requests
if len (sys.argv) < 5:
print "pass in url, username, password, file"
else:
url = sys.argv[1]
username = sys.argv[2]
password = sys.argv[3]
phile = sys.argv[4]
if os.path.exists(phile):
files = {'file': open( phile, 'rb' )}
r = requests.post( url, files=files, auth=( username, password ) )
if r.status_code == 200:
json_response = r.json()
if json_response['success']:
print "id: " + str( json_response['id'] )
else:
print "failure in processing bundle"
else:
print "server problem: " + str(r.status_code)
print r.text
else:
print "cannot find file to upload"
答案 0 :(得分:1)
Content-Type标头是completely arbitrary(并且是可选的),并不是检测您是否正在处理有效ZIP文件的好方法。你确定你的浏览器正在提供它吗?
Django's documentation告诉我们相同的事情:
<强> UploadedFile.content_type 强> 随文件一起上传的内容类型标题(例如text / plain或application / pdf)。与用户提供的任何数据一样,您不应该这样做 相信上传的文件实际上是这种类型。你还需要 验证该文件是否包含content-type的内容 标题声明 - “信任但验证。”
您应该使用zipfile.is_zipfile
代替。