繁体   English   中英

如何使用Ajax发送图像

[英]How can I send the image using Ajax

我想知道如何使用javascript ajax函数将图像数据发送到服务器(Django应用)。

以下是我的代码。

// Get filename of image
jsondata = JSON.parse(data);
image_file_name = jsondata.fileurl;
// document.getElementById('previewimage').src = image_file;
// I can show the image.

b64_image = btoa(unescape(encodeURIComponent(image_file)));
var credentials = {
    filename: image_file_name,
    image: b64_image,
};

// Send ajax request to the server
$.ajax({
    url: HOST_NAME + "user/api/file_uploader/",
    type: 'GET',
    dataType: 'json',
    data: credentials,
    timeout: 10000,
})
.done(function (data) {

    // Get the result
    jsondata = JSON.parse(data);
    alert("File upload completed...");

})
// If false...
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
    console.log("Upload error");
})

您必须使用FromData通过ajax发布文件。

var form = $('form')[0];
var formData = new FormData(form);

$.ajax({
  url: "ajax_php_file.php", // Url to which the request is send
  type: "POST",             // Type of request to be send, called as method
  data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
  contentType: false,       // The content type used when sending data to the server.
  cache: false,             // To unable request pages to be cached
  processData:false,        // To send DOMDocument or non processed data file it is set to false
  success: function(data)   // A function to be called if request succeeds
  {
    // success code .
  }
});

您只需要在代码中进行一项更改。

// Send ajax request to the server
$.ajax({
     url: HOST_NAME + "user/api/file_uploader/",
     type: 'POST',        // changed from GET to POST  
     dataType: 'json',
     data: credentials,
     timeout: 10000,
  })
 .done(function (data) {
  // Get the result
 })
 .fail(function (XMLHttpRequest, textStatus, errorThrown) {
   console.log("Upload error"); 
 })

因为GET用于读取,而post用于创建。 您可以阅读有关请求方法的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM