form表单上传图片文件

import os
def upload(request):

    if request.method == 'GET':

        img_list = models.Img.objects.all()
        return render(request, 'upload.html', {'img_list':img_list})
    elif request.method == 'POST':

        upload_name = request.POST.get('name')
        file_obj = request.FILES.get('image')
        
        
        """
            只能获取文件的名字:
            file_name = request.POST.get('image')
        """
        file_path = os.path.join('static', 'upload', file_obj.name)

        f = open(file_path, 'wb')
        for chuck in file_obj.chunks():
            f.write(chuck)

        f.close()

        models.Img.objects.create(file_path=file_path)

        return redirect('/upload.html')
原文地址:https://www.cnblogs.com/jiefangzhe/p/10779874.html