[英]How to mimic refresh behaviour in javascript?
用戶在瀏覽器中上傳 2 張圖像后,我在服務器上進行了一些處理,然后再次將結果附加到 web 上。 它運行良好,但為了再次執行此操作,用戶必須刷新頁面,否則服務器會崩潰。
我如何修改此代碼以使其像這樣工作:用戶上傳 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
您必須每次都創建一個新的 FormData object ,否則您只是在相同的名稱索引中添加更多項目,並且您的服務器還沒有准備好接受這種格式:
const fd = new FormData(); fd.append("foo", "bar"); fd.append("foo", "baz"); new Response( fd ).text().then( console.log );
所以移動const formData = new FormData();
在onchange
處理程序內部。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.