django2.1 layui 上传附件 动态设置路径与文件名

最终效果:

image.png

layui上传功能链接:
https://www.layui.com/demo/upload.html

输出框也请参考layui样式
https://www.layui.com/demo/form.html

前端唯一区别就是在点击【开始上传】按钮时,如何把路径也post到后端,差别代码如下:

...
var demoListView = $('#demoList')
            , uploadListIns = upload.render({
            elem: '#testList'
            , url: "{% url 'fileapp:fileupload' %}"
            , accept: 'file'
            , multiple: true
            ///////
            ////////// 在这里直接加上后台获取不到数据
           //{#, data:{"path": $("#id_uploadpath").val()}#}
            , auto: false
            , bindAction: '#testListAction'
            ,
            /////////
            /////// 增加before ↓
            before: function (obj) {
                this.data = {"path": $("#id_uploadpath").val()}
            },
            /////↑
            choose: function (obj) {
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            ...

创建数据表models.py

from django.db import models
from django.contrib.auth.models import User
import datetime

# Create your models here.


def path_and_rename(instance, filename):
    # 时间戳
    overdate = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    # ['filename', 'suffix']
    fname = filename.split('.')
   # 拼成新文件名
    newname = fname[0] + '_' + overdate + '.' + fname[1]
   # 由于upload_to 参数需要填写 相对路径,所以要先把最左边的 / 去掉
    return instance.path.lstrip('/') + '/' + newname


class FileUpload(models.Model):
    uploader = models.ForeignKey(User, on_delete=models.DO_NOTHING)
    file = models.FileField(upload_to=path_and_rename, blank=True)
    path = models.CharField(max_length=128, blank=True, null=True)
    date = models.DateTimeField(auto_now_add=True)

相关文档链接
https://docs.djangoproject.com/zh-hans/2.1/ref/models/fields/#filefield

顺便也配置settings.py的 MEDIA_ROOT 属性

views.py

...
try:
    # pdb.set_trace()
    reloadpath = request.POST["path"]
    status = 0
    # django 会自动创建目录
    if not reloadpath:
        raise Exception
    #    path = reloadpath.strip().rstrip('/')
    #    isExists = os.path.exists(path)
    #    if not isExists:
    #        os.makedirs(path)
    #else:
    

    fupload = FileUpload.objects.create(uploader=request.user,
                                                file=request.FILES['file'],
                                                path=reloadpath)

 except Exception as e:
     status = 1
...

UP

你可能感兴趣的:(django2.1 layui 上传附件 动态设置路径与文件名)