如果您问的是“通过 AJAX 上传图片”,那么使用FormData
答案可以更简单,也更容易在互联网上搜索。
请查看是否this link
解决了您的问题。
要从 DOM 中获取图像,您将使用上述相同的方法。但不是提交表单,而是将 DOM img 元素读取为dataURI
.
检查FIDDLE以获取以下代码的 HTML:
var originalImage = document.getElementById("image"),
canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
formdata = false,
dummy = document.getElementById('dummy'),
newImage = new Image();
if (window.FormData) {
formdata = new FormData();
}
newImage.onload = function(){
// width and height here should be the same as original image
// detect before-hand, using jQuery(el).width() /.height() on the DOM element
context.drawImage(newImage, 0, 0, 400, 300);
}
newImage.src = originalImage.src;
// traditional ajax and jQuery, no HTML5
if (formdata) {
var canvasToDURI = canvas.toDataURL();
formdata.append("image-data", canvasToDURI);
// yay!, jQuery
$.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
// do some thing !
dummy.innerText = 'Image data sent !';
},
error: function(a, b, c) {
dummy.innerText = 'The following data was not sent due to : ' + b + ' -- '+ c + ' \n\n' + canvasToDURI;
}
});
}
如果FormData
也不支持,您可以创建一个表单element
并将其更改enctype
为form
并"multipart/form-data"
在 AJAX 调用中使用 JavaScript 发送数据,而无需提交表单。