gpt4 book ai didi

javascript - 如何使用 Ajax 发送图像

转载 作者:行者123 更新时间:2023-11-28 17:47:29 24 4
gpt4 key购买 nike

我想知道如何使用 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 .
}
});

关于javascript - 如何使用 Ajax 发送图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46360468/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com