Django 的多文件上传代码

Multiple File Upload Code for Django

好的。所以我在 Whosebug 中搜索了很多论坛和其他帖子后想出了以下代码。首先,我尝试使用 request.FILES.get('onefile'),但无论我在上传过程中选择了多少,它都只上传了一个文件。所以我稍微更改了我的代码以上传名称为 file1、file2 等的文件。以下是我的代码,但我不知道为什么这不起作用。当前没有正在上传文件,它显示以下代码下列出的错误。

upload2.html

<!DOCTYPE html>

<html>

<head>
</head>

<body>
    <form method="post" action="/index/multi/" enctype="multipart/form-data"> {% csrf_token %}
        <input type="file" name="onefile" multiple>

        <input type="submit" value="Upload">
    </form>
</body>

</html>

views.py

from django.shortcuts import render
from django.http import HttpResponse

def upload2(request):
    return render(request, "upload2.html", {})

def multi(request):
    count = 1
    for x in request.FILES.getlist('onefile'):
        print request.FILES.getlist('onefile')
        def handle_uploaded_file(f):
            with open('/home/michel/django/upload/media/file' + count, 'wb+') as destination:
                for chunk in f.chunks():
                    destination.write(chunk)
        handle_uploaded_file(x)
        count = count + 1
    return HttpResponse('Uploaded!')

urls.py

from django.conf.urls import url

from index import views

urlpatterns = [
    url(r'^upload2/$', views.upload2),
    url(r'^multi/$', views.multi),
]

错误

TypeError at /index/multi/
cannot concatenate 'str' and 'int' objects
Request Method: POST
Request URL:    http://localhost:8000/index/multi/
Django Version: 1.8.1
Exception Type: TypeError
Exception Value:    
cannot concatenate 'str' and 'int' objects
Exception Location: /home/michel/django/upload/index/views.py in handle_uploaded_file, line 32

我不确定我是否遗漏了什么。如果您还需要什么,请告诉我。提前致谢!

连接错误,不能连接'str'和'int'对象。

我认为问题出在这一行

'/home/michel/django/upload/media/file' + count

解决方案

'/home/michel/django/upload/media/file' + str(count)

示例:

a = 'test'
b = 1
c = a+b
Type Error: cannot concatenate 'str' and 'int' objects

解决方案:

a = 'test'
b = str(1) or '1'
c = a+b(works fine)

I'm not sure whether I've missed something.

是:阅读错误消息 - 告诉您错误是什么 - 回溯 - 告诉您错误发生的位置 - 然后重新阅读您的代码。所以你有:

Exception Type: TypeError Exception Value:
cannot concatenate 'str' and 'int' objects

这意味着您试图连接一个字符串和一个整数(Python 不允许,原因很明显)。

Exception Location: /home/michel/django/upload/index/views.py in handle_uploaded_file, line 32

这意味着错误在 /home/michel/django/upload/index/views.py 的第 32 行。

/home/michel/django/upload/index/views.py 的第 32 行是:

with open('/home/michel/django/upload/media/file' + count, 'wb+') as destination:

显然,'/home/michel/django/upload/media/file' + count 是罪魁祸首。现在你只需要解决这个问题,要么制作一个 count 的字符串,要么使用字符串格式化 - 两者都在 FineManual(tm).

中进行了解释

在学习的同时,您可能还想阅读有关内置 enumate(sequence) 函数的信息。