Python Django- How do I get file path from an input file tag in a form?

99封情书 提交于 2021-02-10 06:34:26

问题


I just need the file path. This is what I came with so far:

index.html:

<form enctype="multipart/form-data" action="{% url 'polls:search_for_match' %}" method="post">
            {% csrf_token %}        
                <label for="file_path"></label> <input type="file"
                class="form-control" id="file_path" name="file_path" >
                <button type="submit" class="btn btn-default" >Analyze!</button>
</form>

view.py

def searchMatch(request):
    form_class = Query
    if request.method == 'POST':
        form = form_class(request.POST, request.FILES)
        **file = request.FILES['file_path']**
        last_restarts = request.POST.get('restarts' , '')
                with zipfile.ZipFile(file) as z:
                     .....

forms.py

class Query(forms.Form):
    file_path = forms.FileField()

the problem is in this line: file = request.FILES['file_path'].read()

I don't get the file path, only the file name.


回答1:


The file path from the client can't possibly be of any use to you. Your server application has no access to arbitrary paths on the client, for obvious security reasons.

File inputs provide the file itself for upload; that's all you can access, and all you should need.



来源:https://stackoverflow.com/questions/40283595/python-django-how-do-i-get-file-path-from-an-input-file-tag-in-a-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!