2016-09-25 56 views
5

koa-router ile Koa'da bir POST istek işleyicisinden bir karşıdan yüklemeyi tetiklemeye çalışıyorum. Esasen, böyle bir şey yapmaya çalışıyorum:Koa'da bir POST isteği dosya indir

app.js

const Koa = require('koa') 
const router = require('./router') 

const app = new Koa() 

app.use(router.routes()) 
app.use(router.allowedMethods()) 

app.listen(3000) 

router.js

const fs = require('fs') 
const Router = require('koa-router') 

const router = new Router() 

router.post('/generate', function *() { 
    const path = `${__dirname}/test.txt` 
    this.body = fs.createReadStream(path) 
    this.set('Content-disposition', 'attachment; filename= test.txt') 
}) 

module.exports = router 

client.js

const { fetch } = window; 

const request = { 
    method: 'POST', 
    body: JSON.stringify({ fake: 'data' }) 
} 

// Make the POST request 
fetch('/generate', request) 

Ancak, POST isteği gönderildiğinde hiçbir şey olmuyor. Sunucu konsolunda veya tarayıcı konsolunda da herhangi bir hata alamıyorum. Herhangi bir yardım takdir edilecektir!

+0

Ben senin sorunun sunucu tarafı kod ama istemci tarafında olmadığını düşünüyorum. Alınan verilerle ne yaptığınızı gösterir misiniz? getirme form teslim olarak çalışmayacak, yanıtı işlemek zorunda ve eğer Vedran onun müşteri tarafında kod ne yaptığını indirmek istiyorsanız. –

cevap

4

Sen https://github.com/koajs/send

router.post('/generate', function * (next) { 
    yield send(this, 'file.txt'); 
}); 

Ve istemci tarafında kullanarak deneyebilirsiniz, yayının istek üzerinden dosya içeriğini aldıktan sonra oluşturmak ve tetik indir gerekir. Sen vücutta dosya akışı ayarlamak ve bu dosya adıyla eki Content-disposition göndermesi gerektiğini isteği geri aramasında

fetch('/generate', request) 
    .then(res => { return res.text() }) 
    .then(content => { 

    uriContent = "data:application/octet-stream," + encodeURIComponent(content); 

    newWindow = window.open(uriContent, 'somefile'); 

    }); 
+0

Bu kod benim için çalışmıyor gibi görünüyor. Basit bir örneğe sahip olma şansınız var mı? – saadq

+0

Yayımlandı github repo https://github.com/vedranjukic/downloadkoademo Sadece klon ve npm kurulum. Uygulamayı node app.js ile çalıştırın ve chrome localhost: 3000'i açın ve test etmek için indirme düğmesine tıklayın. Bunu olabildiğince basit yapmaya çalıştım. İşe yarıyorsa haber ver. –

+0

Vay, sadece sorunun ne olduğunu anladım. Ben 'UBlock Origin' benim popup engelleyici olarak yüklü vardı ve bu indirme önlenmesi gibi görünüyor. Aptalca sorun için özür dilerim, yanıt için teşekkürler! – saadq

4

bu kodu koyun. kodunun altına

const Router = require('koa-router'); 
const router = new Router(); 

router.post('/generate', function *() { 
    const path = `${__dirname}/file.txt`; 
    this.body = fs.createReadStream(path); 
    this.set('Content-disposition', 'attachment; filename= file.txt'); 
}); 

module.exports = router; 

GÜNCELLEME kullanın: Komple çalışma kodu:

var app = require('koa')(); 
var router = require('koa-router')(); 
const fs = require('fs'); 
router.post('/generate', function() { 
    const path = `${__dirname}/file.txt`; 
    this.body = fs.createReadStream(path); 
    this.set('Content-disposition', 'attachment; filename= file.txt'); 
}); 

app 
    .use(router.routes()) 
    .use(router.allowedMethods()); 

    app.listen(3000); 

Client:

<button id="btnDownload">Download</button> 

<script type="text/javascript"> 
    const request = { 
     method: 'POST', 
     body: JSON.stringify({ 
      fake: 'data' 
     }) 
    } 

    document.getElementById('download').onclick =() => { 
     fetch('/generate', request) 
      .then(res => { 
       return res.text() 
      }) 
      .then(content => {}); 
    } 
</script> 
+0

Bu temelde yapmaya çalıştığım şey, ama işe yaramıyor. Gönderiyi tam kodumu eklemek için güncelledim, sorunun ne olduğunu biliyorsanız lütfen bildirin. – saadq

+0

Temel olarak, POST isteği gönderildiğinde, tarayıcımda hiçbir şey olmuyor. Dosya indirileceğini düşündüm? – saadq

+0

@meh_programmer, yazım ekini kullandığınız için .this.set ('Content-disposition', 'attchment; filename = test.txt'). "eki" olarak "eki" olarak değiştirin; :) – Sachin

0

aynı işlevselliği bu tercih download.I bir etiketi kullanılarak elde edilebilir. JS olmadan çalışır, ancak safari içinde değildir.

<!DOCTYPE html> 
<html> 
<body> 

<p>Click on the w3schools logo to download the image:<p> 

<a href="http://www.w3schools.com/images/myw3schoolsimage.jpg" download> 
    <img border="0" src="http://www.w3schools.com/images/myw3schoolsimage.jpg" alt="W3Schools" width="104" height="142"> 
</a> 

<p><b>Note:</b> The download attribute is not supported in Edge version 12, IE, Safari or Opera version 12 (and earlier).</p> 

</body> 
</html> 

refernce: http://www.w3schools.com/tags/att_a_download.asp