所以我使用标准的上传文件代码在我的网站上制作上传功能。我测试过的所有文件类型(pdf,gif,jpg)似乎都运行正常,但是当我尝试上传docx文件时,Django将该文件存储为.zip文件。显然这与“内容嗅探”有关?这是代码 -
def upload_form(request):
if request.method == 'POST':
# Gets the information about the file
uploaded_file = request.FILES['file']
file_size, file_name = uploaded_file.size, "ID" + str(File.objects.all().count()) + "%" + request.POST['name']
# Stops the processing if the file size is too large
if(file_size > 5242880):
return render_to_response('upload_form.html', { 'large_file' : '1' }, context_instance=RequestContext(request))
file_path, file_course = '/home/simon/Centum/static/notes/' + file_name, request.POST['course']
# Reads and writes the chunks
with open(file_path, 'wb+') as destination:
for chunk in request.FILES['file'].chunks():
destination.write(chunk)
# Saves the file
upload = File(
name = file_name,
real_name = file_name[file_name.find('%') + 1:],
user = request.user,
path = file_path,
size = int(file_size),
course = file_course.upper(),
date_uploaded = datetime.datetime.now()
)
upload.save()
return render_to_response('upload_form.html', {'success' : '1'}, context_instance=RequestContext(request))
无论如何要让它在上传时保持为.docx?
答案 0 :(得分:0)
docx文件 是一个zip文件。如果django使用zip扩展名保存它并不会改变内容并且您可以使用您喜欢的任何文件名提供它并不重要。你面临的实际问题是什么?