我尝试使用此代码保存图像。它将图像保存在给定路径中,但不会获取文件名。我怎么能得到它?
@csrf_exempt
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if 'filename' in request.FILES:
filename = request.FILES['filename'].name
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/user_profileform/')
else:
form = UploadFileForm()
return render_to_response('user_profile.html', {'form': form })
def handle_uploaded_file(f):
destination = open('media/filename', 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
答案 0 :(得分:1)
您似乎想重复使用文件名来保存文件,您可以尝试:
def handle_uploaded_file(f):
filename = f.name # get the name here
destination = open('media/'+filename, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
在upload_file
视图中,也存在错误:
@csrf_exempt
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if 'filename' in request.FILES:
# filename = request.FILES['filename'].name # remove this line, you don't need it
if form.is_valid():
handle_uploaded_file(request.FILES['filename']) # should be filename here
#.... your code ....
希望它有所帮助。
答案 1 :(得分:0)
这可能是编码错误。您的POST是否编码为UTF-8?这意味着在HTML中有类似的东西:
<meta charset="UTF-8" />