我有点困惑,这是一种预期的行为吗?
Javascript - Sample 01
function convertCanvasToImage() {
var temp_ctx, temp_canvas;
temp_canvas = document.createElement('canvas');
temp_ctx = temp_canvas.getContext('2d');
temp_canvas.width = windowWidth;
temp_canvas.height = windowWidth;
temp_ctx.drawImage(ctx.canvas, cutoutWidth, cutoutWidth, windowWidth, windowWidth, 0, 0, windowWidth, windowWidth);
var multiPart = new FormData();
temp_canvas.toBlob(function (blob) {
//Tilføjer blob til form objektet
multiPart.append('pernille', blob, ".jpg");
//Ajax kaldet
var http = new XMLHttpRequest();
var url = "ajax.php";
http.open("POST", url, true);
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
alert(this.responseText);
console.log(this.responseText);
}
};
http.send(multiPart);
}, "image/jpeg");
}
Javascript - 样本02
function convertCanvasToImage() {
var temp_ctx, temp_canvas;
temp_canvas = document.createElement('canvas');
temp_ctx = temp_canvas.getContext('2d');
temp_canvas.width = windowWidth;
temp_canvas.height = windowWidth;
temp_ctx.drawImage(ctx.canvas, cutoutWidth, cutoutWidth, windowWidth, windowWidth, 0, 0, windowWidth, windowWidth);
var multiPart = new FormData();
temp_canvas.toBlob(function (blob) {
//Tilføjer blob til form objektet
multiPart.append('pernille', blob, "pernille");
//Ajax kaldet
var http = new XMLHttpRequest();
var url = "ajax.php";
http.open("POST", url, true);
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
alert(this.responseText);
console.log(this.responseText);
}
};
http.send(multiPart);
}, "image/jpeg");
}
的Ajax
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$file = current($_FILES);
$nameparts = pathinfo($file['name']);
echo "<pre>";
echo '$_POST';
print_r($_POST);
echo '$_FILES';
print_r($file);
echo 'pathinfo';
print_r($nameparts);
echo "</pre>";
}
两个javascript函数的区别在于这两行
Func 01
multiPart.append('pernille', blob, ".jpeg");
Func 02
multiPart.append('pernille', blob, "pernille");
Javascript示例01将从AJAX调用中输出 没有文件名?
<pre>$_POSTArray
(
)
$_FILESArray
(
[name] => .jpg
[type] => image/jpeg
[tmp_name] => /home/xch07.wi2/tmp/phpZ6zxv2
[error] => 0
[size] => 17713
)
pathinfoArray
(
[dirname] => .
[basename] => .jpg
[extension] => jpg
[filename] =>
)
</pre>
Javascript示例02将从AJAX调用输出这个文件名但没有扩展名吗?
<pre>$_POSTArray
(
)
$_FILESArray
(
[name] => pernille
[type] => image/jpeg
[tmp_name] => /home/xch07.wi2/tmp/phpaKQwU4
[error] => 0
[size] => 17601
)
pathinfoArray
(
[dirname] => .
[basename] => pernille
[filename] => pernille
)
</pre>
答案 0 :(得分:3)
这并不是很奇怪,而是你错误地使用 FormData.append()
方法。
正确的表格应该是:
multiPart.append('pernille', blob, 'pernille.jpeg');
^ ^ ^
field-name data-value file-name
您需要使用文件名本身附加文件扩展名。
请参阅here了解详情。