首页 > 解决方案 > 将文件对象保存到文件中 - 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 传递)保存在服务器上的一个文件中,但我不知道该怎么做。

标签: javascriptphpsweetalert2

解决方案


我通过使用 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)
        }

推荐阅读