Django保存上传的文件

时间:2018-04-24 06:43:57

标签: python django save

我想上传一个文件,我可以用下面描述的代码做什么,但我还需要将所有上传文件保存在不同名称的不同文件夹中。如果2个用户从浏览器上传相同的文件,则应在该文件夹中使用不同的名称或唯一标识号保存。 以下是我的代码:

views.py

from django.shortcuts import render
import openpyxl


def index(request):
    if "GET" == request.method:
        return render(request, 'myapp/index.html', {})
    else:
        excel_file = request.FILES["excel_file"]

        # you may put validations here to check extension or file size

        wb = openpyxl.load_workbook(excel_file)

        # getting all sheets
        sheets = wb.sheetnames
        print(sheets)

        # getting a particular sheet
        worksheet = wb["Sheet1"]
        print(worksheet)

        # getting active sheet
        active_sheet = wb.active
        print(active_sheet)

        # reading a cell
        print(worksheet["A1"].value)

        excel_data = list()
        # iterating over the rows and
        # getting value from each cell in row
        for row in worksheet.iter_rows():
            row_data = list()
            for cell in row:
                row_data.append(str(cell.value))
                print(cell.value)
            excel_data.append(row_data)

        return render(request, 'myapp/index.html', {"excel_data":excel_data})

1 个答案:

答案 0 :(得分:0)

给你一个Django FileField方法实现:

def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    suffix = filename[filename.rindex(".")+1:]
    return 'upfiles/{0}/{1}.{2}'.format(instance.user.username, get_randomfilename(),suffix)

class Picture(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    file = models.ImageField(upload_to=user_directory_path)
    date_added = models.DateTimeField(auto_now_add=True)
@parser_classes((MultiPartParser,))
@permission_classes((IsAuthenticated, ))
def upload_picture(request):
    '''
    :input :{"file":f}
    :return:{"id":pictureId}
    '''
    if "file" in request.FILES:
        f = request.FILES["file"]
        picture = Picture()
        picture.user= request.user
        picture.file = f
        picture.save()
        return Response(data={"id":picture.id})
    else:
        return Response({},status=status.HTTP_400_BAD_REQUEST)