使用Django和Python将文件存储到文件夹时出错。我在解释下面的错误。
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/opt/lampp/htdocs/rework/Nuclear/RFI15/vlnerable/plant/views.py", line 267, in downloadfile
fyl.write(response)
TypeError: expected a character buffer object
[12/Sep/2017 10:52:35] "POST /downloadfile/ HTTP/1.1" 500 71558
Performing system checks...
我正在解释下面的代码。
def downloadfile(request):
""" This function helps to download the file from remote site"""
if request.method == 'POST':
URL = request.POST.get('file')
filename = "status.txt"
response = HttpResponse(content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename='+filename
with open(settings.FILE_PATH + filename, 'w') as fyl:
fyl.write(urllib2.urlopen(URL).read())
fyl.write(response)
return response
我在此fyl.write(response)
行中收到了该错误。在这里,我包括远程文件并下载它。下载后将其存储在文件夹中。
答案 0 :(得分:1)
import os
from django.conf import settings
from django.http import HttpResponse
def download(request, path):
if request.method == 'POST':
URL = request.POST.get('file')
path_with_filenmae = "status.txt" #you can define file name with path
file_path = os.path.join(settings.MEDIA_ROOT, path_with_filenmae)
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="text/plain")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
raise Http404
答案 1 :(得分:0)
有关于使用Django在SO上进行文件上传的详细示例:Need a minimal Django file upload example
夏天:
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
这里的博文:https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html