使用 Ajax 时无法将文件上传到 Django 中的媒体路径

Cannot upload file to media path in Django when using Ajax

我正在尝试将图像文件上传到我的 setting.py 中指定的媒体 url 并且 将图像的路径存储在数据库中 table。 但是,当使用 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>

Ajax :

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' - 这个值应该存储在我的数据库中 table.

settings.py

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

问题不在于 Django,而在于您的 AJAX post,您只是传递名称,因此 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