代码之家  ›  专栏  ›  技术社区  ›  maicol07

将文件对象保存到一个文件中-sweetelert2-javascript-php

  •  0
  • maicol07  · 技术社区  · 6 年前

    我设置了一个带有文件输入的SweetAlert2弹出窗口(仅允许图像),根据 example :

    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文件会将由sweetelert2输入(然后通过xmlhttprequest)生成的文件对象保存在服务器上的一个文件中,但我不知道如何执行此操作。

    1 回复  |  直到 6 年前
        1
  •  0
  •   maicol07    6 年前

    我通过使用JS阅读器解决了这个问题,从中读取数据URI,然后使用后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)
            }