将文件对象保存到文件中 - sweetalert2 - javascript - php
Save file object into a file - sweetalert2 - javascript - php
根据example:
,我设置了一个带有文件输入的 SweetAlert2 弹出窗口(只允许图像)
const {value: file} = await swal({
title: "Image upload",
text: "Upload your profile image",
input: 'file',
inputAttributes: {
'accept': 'image/*',
'aria-label': "Upload here your image"
}
});
然后我通过 XMLHTTPRequest 向 PHP 文件发送了一个 ajax 请求:
if (file) {
if (!file) throw null;
swal.showLoading();
if (window.XMLHttpRequest) {
// code for modern browsers
var xmlhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
// success message
};
xmlhttp.open("GET", "includes/uploadimage.php?image=" + file, true);
xmlhttp.send();
}
PHP文件会将SweetAlert2输入(然后通过XMLHttpRequest传递)生成的文件对象保存在服务器上的一个文件中,但我不知道该怎么做。
我通过使用 JS reader 解决了这个问题,从中读取数据 URI 并使用 POST XMLHttpRequest 通过 FormData 发送它。
if (file) {
if (!file) throw null;
swal.showLoading();
const reader = new FileReader;
reader.onload = (e) => {
const fd = new FormData;
fd.append('image', e.target.result);
if (window.XMLHttpRequest) {
// code for modern browsers
var xmlhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
// ... do something ...
};
xmlhttp.open("POST", "includes/uploadimage.php", true);
xmlhttp.send(fd);
};
reader.readAsDataURL(file)
}
根据example:
,我设置了一个带有文件输入的 SweetAlert2 弹出窗口(只允许图像)const {value: file} = await swal({
title: "Image upload",
text: "Upload your profile image",
input: 'file',
inputAttributes: {
'accept': 'image/*',
'aria-label': "Upload here your image"
}
});
然后我通过 XMLHTTPRequest 向 PHP 文件发送了一个 ajax 请求:
if (file) {
if (!file) throw null;
swal.showLoading();
if (window.XMLHttpRequest) {
// code for modern browsers
var xmlhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
// success message
};
xmlhttp.open("GET", "includes/uploadimage.php?image=" + file, true);
xmlhttp.send();
}
PHP文件会将SweetAlert2输入(然后通过XMLHttpRequest传递)生成的文件对象保存在服务器上的一个文件中,但我不知道该怎么做。
我通过使用 JS reader 解决了这个问题,从中读取数据 URI 并使用 POST XMLHttpRequest 通过 FormData 发送它。
if (file) {
if (!file) throw null;
swal.showLoading();
const reader = new FileReader;
reader.onload = (e) => {
const fd = new FormData;
fd.append('image', e.target.result);
if (window.XMLHttpRequest) {
// code for modern browsers
var xmlhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
// ... do something ...
};
xmlhttp.open("POST", "includes/uploadimage.php", true);
xmlhttp.send(fd);
};
reader.readAsDataURL(file)
}