javascript - 将文件对象保存到文件中 - sweetalert2 - javascript - php
问题描述
根据示例,我设置了一个带有文件输入的 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 阅读器解决了这个问题,从它读取数据 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)
}
推荐阅读
- python - 使用 pandas 的滚动统计模型协整
- javascript - 为来自 State 的初始表单值的 Redux 表单编写 Jest 测试时出错
- rust - 在接受特征对象的方法中使用关联函数
- c# - C# 7.3 只读结构类型“this”参考
- php - foreach 循环读取具有三个用户的数组中的元素
- objective-c - 无法在服务应用程序的 NSTableView 中选择行
- jquery - 如何在 div 之外定位多个类
- wildfly-swarm - Wildfly-swarm 8.5.0 创建系统属性而不是根元素
- python - python 使用 concurrent.futures 库进行 SHA256 + salt 加密
- c++ - 如何保存对抽象基类的指针/引用但仍可在 C++ 中复制