【问题标题】:Cannot upload file to media path in Django when using Ajax使用 Ajax 时无法将文件上传到 Django 中的媒体路径
【发布时间】:2015-10-06 07:53:32
【问题描述】:

我正在尝试将图像文件上传到我的 setting.py 中指定的媒体 url 和 将图像的路径存储在数据库表中。 但是,当使用 Ajax 上传图像文件时,我无法实现这一点。.

template.html

<div class="profpic" style="background:url(../../../static/app/img/test.png);background-size:cover">
            <input type="file" id="picpath" name="picpath" class="uploadpic" value=""/>
        </div>

阿贾克斯:

function saveprof() {
            $.ajax({
                type: "POST",
                url: "saveprof",
                enctype: 'multipart/form-data',
                async: true,
                data: {
                    'picpath_Aj': $('#picpath').val(),
                    'profemail_Aj': $('#profemail').val(),
                    'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
                },
                success: function (data, textStatus, jqXHR) {
                    $('#message').html(data);
                }
            });
        }

Views.py

def saveprof(request):
if request.method == "POST":
    picpathV = request.POST['picpath_Aj']
else:
    profemailV = ''
    response_data = 'Nothing to update!'
    return HttpResponse(response_data, content_type="text/plain")
response_data = 'Empty'
try:
    res=td_table.objects.filter(id=request.session.get('proid')).update(picpath=picpathV)
except:
    response_data = 'Something went wrong!'
return HttpResponse(response_data, content_type="text/plain")

上面的代码工作正常,但我只能保存文件路径,如 ('C:\fakepath\file.jpg').. 并且文件没有保存到媒体 Settings.py 中提供的路径。

当我在视图中使用 request.FILES 时,当使用 Django 表单时,我可以上传文件。但就我而言,我只需要使用 Ajax 函数来完成此操作。 视图代码可能有什么问题?

这是我的models.py

class td_Student(models.Model):
firstname = models.CharField(max_length=300,blank=True)
picpath=models.FileField(upload_to=unique_filename)

def unique_filename(instance, filename):
    ext = filename.split('.')[-1]
    filename = "%s_%s.%s" %(uuid.uuid4(),time.strftime("%Y%m%d_%H%M%S"), ext)
    return os.path.join('documents/documents/'+time.strftime("%Y%m%d"), filename)

根据上述逻辑,文件名应类似于“documents/documents/20150716/a1f81a80-ce6f-446b-9b49-716b5c67a46e_20150716_222614.jpg” - 此值应存储在我的数据库表中。

settings.py

MEDIA_ROOT = 'C:/DJ/'
MEDIA_URL = '/DJ/'

【问题讨论】:

    标签: python ajax django django-views


    【解决方案1】:

    问题不在于 Django,而在于您的 AJAX 帖子,您只是传递名称,因此 Django 接收并保存名称。

    Solution: 一旦用户选择了一个文件,change 事件将被发出,在此更改事件中,您必须使用event.target.files 获取文件实例,并将其存储在局部变量中并将其传递给picpath_Aj' .

    // Add events
    $('input[type=file]').on('change', prepareUpload);
    
    // Grab the files and set them to our variable
    function prepareUpload(event)
    {
      files = event.target.files;
    }
    

    详细指南在这里http://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax

    带有 JS 和后端代码的替代 Django 解决方案是 https://github.com/skoczen/django-ajax-uploader

    【讨论】:

    • 谢谢库马尔。我会试试这个方法。我想,Django 本身可能有一些我错过了的可能性.. 但这也很有用。
    • Sathish,Django 是服务器端,无法通过路径访问客户端文件,因此文件流必须通过 JS 或 HTML 表单从客户端上传。
    • 我同意。但是我需要在 Django 中编写服务器端代码以根据给定的示例在放弃.ie 中上传文件。您是否遇到过任何使用 Ajax 和 Python django 上传文件的工作示例,而无需 html 表单?
    • 嗨 Kumar,我有一个问题.. 我可以使用表单上传文件并通过我的 Ajax 方法发送表单数据吗?这可能吗?如果可以,DJango 可以将上传的文件存储在服务器中。
    • 是的,这就是我给出的 JS 所做的,它从文件 inout 字段中读取并获取文件实例。因此,您可以在通过 Ajax 发布时使用该实例,但请阅读完整指南,内容类型等有一些注意事项。
    猜你喜欢
    • 2019-07-01
    • 2016-04-14
    • 2020-11-29
    • 2016-02-21
    • 2021-11-03
    • 2019-10-14
    • 2023-03-15
    • 2016-06-08
    • 2021-12-12
    相关资源
    最近更新 更多