首页 > 解决方案 > 如何模仿javascript中的刷新行为?

问题描述

用户在浏览器中上传 2 张图片后,我在服务器上进行了一些处理,然后再次将结果附加到网络上。它运行良好,但为了再次执行此操作,用户必须刷新页面,否则服务器会崩溃。
我如何修改此代码以使其像这样工作:用户上传 2 张图片并获得结果后,如果用户选择更改其中一张或两张初始图片,则新结果会再次显示在网页上?

const formData = new FormData();
$('#resbtn').hide();
$(".uploadbuttons").on("change", function(e) {
    const tgt = e.target;
    if (tgt.type !== "file") {
        return;
    }
    if (!tgt.files || !tgt.files[0]) {
        return;
    }
    const reader = new FileReader();
    const idx = tgt.id.replace("picture", "");
    formData.append(`image${idx}`, tgt.files[0]); // append image with index idx
    reader.onload = async function(e) {
        const image = `<img src="${e.target.result}" style="width:20vw;height:auto;" id="image${idx}-morph">`;
        $("#appendimg" + idx).html(image);
        if ($(".uploadbuttons").find("img").length === 2) {
            await fetch('/saveImage', {
                method: 'POST',
                body: formData
            }).then(function(res) {
                // console.log(res.json());
            }).then(function(data) {
                // console.log(data);
            });

            await fetch('/processImg', {
                method: 'POST',
                body: formData
            }).then(async function(res) {
                // console.log(res.json());
                await res.text().then(function(img) {
                    $('#resbtn').show(500);
                    $('#resbtn').on('click', function() {
                        const image = `<img src="${img}" style="width:20vw;height:auto;">`;
                        $("#appendResult").html(image);
                    });
                });
            }).then(function(data) {
                // console.log(data);
            });
        }
    };
    reader.readAsDataURL(tgt.files[0]);
});

服务器帖子如下:

//upload images to server
app.post('/saveImage', function (req, res) {
    console.log("Both images were uploaded, algorithm starting...");
    const files = [req.files.image1, req.files.image2]; // files from request
    const fileNames = [req.files.image1.name, req.files.image2.name];
    const paths = [__dirname + '/uploads/' + fileNames[0], __dirname + '/uploads/' + fileNames[1]];
    //upload images to folder
    for (var i = 0; i < 2; i++) {
        files[i].mv(paths[i], (err) => {
            if (err) {
                console.error(err);
                res.end(JSON.stringify({ status: 'error', message: err }));
                return;
            }
            res.end(JSON.stringify({ status: 'images were successfully saved to the server'}));
        });
    }
});

app.post('/processImg',async function (req, res) {
    const img1Name = req.files.image1.name;
    const img2Name = req.files.image2.name;
    const { outputImg1, outputImg2 } = await processImages(img1Name, img2Name);
    await facialDetection(outputImg1, outputImg2);
    setTimeout(function() {
        const image64 = base64_encode(`${__dirname}\\uploads\\MorphedFace.jpg`);
        removeDir(path.join(__dirname, 'uploads')); //clean folder
        res.send(image64)}, 5000); // wait 5s
});

和 HTML:

<div class="uploadbuttons">
    <form>
        <input type="file" id="picture1">
        <div id="appendimg1"></div>
    </form>
    <form>
        <input type="file" id="picture2">
        <div id="appendimg2"></div>
    </form>
</div>
<div id="getResult">
    <button id="resbtn">Show result</button>
    <div id="appendResult"></div>
</div>
</div>

我在服务器中得到的错误如下(图像路径在新调用 post 之前没有更新):

var name1 = img1Name.split('.')[0]; //get name w/o extension
                         ^
TypeError: Cannot read property 'split' of undefined

标签: javascript

解决方案


您必须每次都创建一个新的 FormData 对象,否则您只是在相同的名称索引处添加更多项目,并且您的服务器还没有准备好接受这种格式:

const fd = new FormData();
fd.append("foo", "bar");
fd.append("foo", "baz");
new Response( fd ).text().then( console.log );

所以在处理程序const formData = new FormData();内部移动onchange


推荐阅读