javascript - 使用 AJAX POST 发布数据

标签 javascript python django xmlhttprequest

是否可以使用 jQuery 的 ajax post 方法来发布图像文件。如果我只是将文件数据放入 POST 请求的“data”参数中可以吗?

我正在使用 django 框架。这是我的第一次尝试:

$('#edit_user_image').change(function(){
    var client = new XMLHttpRequest();
    var file = document.getElementById("edit_user_image");
    var csrftoken = document.getElementsByName('csrfmiddlewaretoken')[0].value
    /* Create a FormData instance */

    var formData = new FormData();
    formData.append("upload", file.files[0]);


    client.open("post", "/upload-image/", true);
    client.setRequestHeader("X-CSRFToken", csrftoken);
    client.setRequestHeader("Content-Type", "multipart/form-data; charset=UTF-8; boundary=frontier");
    client.send(formData);  /* Send to server */ 
  });

问题是我在“views.py”中没有在服务器端获得“request.FILES”对象。

我也尝试过使用 ajax post 来实现,但它也不起作用。

$('#edit_user_image').change(function(){
    var data = {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
                content:document.getElementById("edit_user_image").files[0],}
    $.post("/upload-image/", data, function(){
    });
  });

从答案之一进行编辑:

$('#edit_user_image').change(function(){
    var formData = new FormData($("#edit_user_image")[0]);

    $.ajax({  
      type: "POST", 
      url: "/upload-image/",  
      xhr: function() {  // custom xhr
        // If you want to handling upload progress, modify below codes.
        myXhr = $.ajaxSettings.xhr();
        if(myXhr.upload){ // check if upload property exists
          myXhr.upload.addEventListener('progress', yourProgressHandlingFunction, false); // for handling the progress of the upload
        }
        return myXhr;
      },
      data: formData,  
      // Options to tell JQuery not to process data or worry about content-type
      cache: false,
      contentType: false,
      processData: false,
      beforeSend: function(xhr) {
        // If you want to make it possible cancel upload, register cancel button handler.
        $("#yourCancelButton").click(xhr.abort);
      },
      success: function( data ) {  
        // Something to do after upload success.
        alert('File has been successfully uploaded.'); 
        location.reload();
      },
      error : function(xhr, textStatus) {
        // Something to do after upload failed.
        alert('Failed to upload files. Please contact your system administrator. - ' + xhr.responseText);
      }
    });  
  });

最佳答案

这是我最终的工作解决方案:

$('#edit_user_image').change(function(){
    var csrftoken = document.getElementsByName('csrfmiddlewaretoken')[0].value
    var formData = new FormData($("#edit_user_image")[0]);
    var formData = new FormData(); 
    formData.append("file", $('#edit_user_image')[0].files[0]);
    formData.append("csrfmiddlewaretoken", csrftoken);

    $.ajax({  
      type: "POST", 
      url: "/upload-image/",  
      data: formData, 
      contentType: false, 
      processData: false, 

    });  
  });

关于javascript - 使用 AJAX POST 发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20715606/

相关文章:

javascript - 单击一个元素突出显示其他元素

Javascript:IIfe在类构造函数之前调用

javascript - 在没有任何服务器请求的情况下触发文件下载

python - 循环不会像读取字符串中的其他单词那样读取第一个单词

mysql - 在不损害用户数据的情况下集中登录 Django、MediaWiki 和 Roundup?

JavaScript:操作两个数组

python - 如何使用 tkFileDialog 获取文件的绝对路径?

python - 在 Python 中使用 numpy.random.choice 更快的替代方案?

python - Django 是否以某种方式缓存 url 正则表达式模式?

django - 如何重命名 Django 应用程序并将数据从一个应用程序迁移到另一个应用程序