简体   繁体   English

使用Django视图上传文件

[英]Upload file with Django Views

I am working on a feature for a Django application that uploads files (images in my context) to the server. 我正在为Django应用程序开发一项功能,该功能可以将文件(我的上下文中的图像)上载到服务器。 Everything is working fine but I am wondering how I can receive as callback the uploaded file path. 一切正常,但我想知道如何接收上载的文件路径作为回调。

Here is my View: 这是我的观点:

def post(self, request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['uploadedFile'])
            return redirect('/')
    else:
        form = UploadFileForm()
    return render_to_response('index.html', {'form': form})

My Form: 我的表格:

class UploadFileForm(forms.Form):
    uploadedFile = forms.FileField()

And my handler: 而我的经理:

def handle_uploaded_file(source):
    fd, filepath = tempfile.mkstemp(prefix=source.name, dir=FILE_UPLOAD_DIR)
    with open(filepath, 'wb') as dest:
        shutil.copyfileobj(source, dest)
    return filepath

I know that handle_uploaded_file(request.FILES['uploadedFile']) from my view is the required string that I need as callback but how to receive it in the response? 我知道从我的观点来看, handle_uploaded_file(request.FILES['uploadedFile'])是我需要作为回调的必需字符串,但是如何在响应中接收它呢? It is possible to receive instead of my index.html (it is there just for testing purposes) the path of the image for further manipulation in the frontend part. 可以接收图像的路径而不是我的index.html(仅用于测试目的),以便在前端部分中进行进一步的操作。 I might sound like a noob but I really want if that works somehow. 我听起来像个菜鸟,但我真的想以某种方式奏效。 Also is there a way for my View to handle multiple file upload? 另外,我的视图是否可以处理多个文件上传? It is something that I need to change in my handler? 我需要在处理程序中进行更改吗? Sorry for putting so many questions... 很抱歉提出这么多问题...

Try this: 尝试这个:

file_path = handle_uploaded_file(request.FILES['uploadedFile']) 
return render_to_response('index.html', {'form': form, 'file_path': file_path})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM