Django使用AJAX在图像上传时给出了400个不良请求错误



我正在使用Quill Editor上传图像,并且Ajax函数用于将图像发送到Views.py。

这是上传图像的Python函数。

views.py

def upload_image(request):
    if request.method == 'POST':
        handle_uploaded_file(request.FILES.get('file'))
        return HttpResponse("Successful")
    return HttpResponse("Failed")

def handle_uploaded_file(file):
    with open('upload/', 'wb+' ) as destination:
        for chunk in file.chunk():
            destination.write(chunk)

这是AJAX请求:

function upload(file, callback) {
    console.log('called');
      var formData = new FormData();
      formData.append('file', file);
      $.ajax({
         url : '{% url 'dashboard:upload_image' %} ',
         type : 'POST',
         data : formData,
         contentType: 'multipart/form-data',
         headers: { "X-CSRFToken": $.cookie("csrftoken") },
         processData: false,
         success: function(data) {
            console.log('success');
            callback(data.url)
         }
      });
   }

函数调用上传((:

function(value) {
              let fileInput = this.container.querySelector('input.ql-image[type=file]');
              if (fileInput == null) {
                fileInput = document.createElement('input');
                fileInput.setAttribute('type', 'file');
                fileInput.setAttribute('accept', 'image/*');
                fileInput.classList.add('ql-image');
                fileInput.addEventListener('change', () => {
                  if (fileInput.files != null) {
                    upload();
                  }
                });
                this.container.appendChild(fileInput);
              }
              fileInput.click();
            }
        }

字符串中的错误

with open('upload/', 'wb+' ) as destination:

错误的路径。设置文件名。

最新更新