Django使用ajax在图像上传中给出400 Bad request错误

时间:2017-06-08 06:40:41

标签: django image-uploading bad-request quill

我使用quill编辑器上传图片,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)
         }
      });
   }

函数调用upload():

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();
            }
        }

1 个答案:

答案 0 :(得分:0)

字符串错误

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

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