我正在尝试使用ng文件upload上传csv文件。这是我的代码片段:
Upload.upload({
url: baseUrl + '/file-upload',
data: {
file: file
}
})
.then(function(res) {
console.log('success: ===> ', res);
}, function(err) {
console.log('erroir: ===> ', err);
}, function() {
console.log('progress: ', arguments);
});
在节点环境中,我解析文件并将数据插入数据库。我不想关闭连接。这就是我使用"response.write"的原因。以下是我的代码片段:
var path = req.files.file.path,
currentIndex = 0;
fs.readFile(path, 'utf8', function(err, data) {
if(err) {
// handle error
} else {
// making array (dataArray) from data
dataArray.forEach(function(eachData){
newEntry = new app.db.models.SomeCollection(eachData);
newEntry.save(function(err, data) {
if (currentIndex === dataArray.length) {
res.end('DONE!');
} else {
currentIndex++;
res.write(JSON.stringify({
total: dataArray.length,
done: currentIndex
}));
}
});
})
}
});
我的问题是如何获得我在"res.write"中传递的数据?我不想只为这个目的使用套接字。我是不是错过了什么?
如前所述:
response.send(msg)等于response.write(msg);response.end();
也就是说,发送只能调用一次,写入可以调用多次,但您必须自己调用结束。
您可能没有收到响应,因为缺少response.end()
。
一旦您end()
您的响应,您应该能够在返回的Upload.Upload承诺中访问角度控制器中的响应数据。
这不像您所说的关闭连接。这不是一个类似套接字的实现(例如ws
或socket.io
)。一旦发出请求,即使它要提供关于该请求的错误细节(即状态401、403、404等),它也应该具有响应。
在角度分量中:
...
constructor(private incrementalService: IncrementalService) {}
incrementalTest() { //activate with a button or whatnot
this.incrementalService.increment().subscribe( (result:any) => {
if (result.partialText) {
console.log(partialText); //do whatever you need to do with your partial results here!
}
})
}
您的角度服务:
import { HttpClient, HttpHeaders } from '@angular/common/http';
public class IncrementalService {
constructor(private http: HttpClient) {}
increment(): Observable<ArrayBuffer> {
const options = {
reportProgress: true,
responseType: 'text',
observe: 'events'
}
return this.http.request('get', 'http://someURL', { ...this.addRawHeaderOptions(), ...options});
}
private addRawHeaderOptions() {
const authHeaders = new HttpHeaders({
'Content-Type': 'application/json',
//authorization, Cache-Control: 'no-cache, Pragma:'no-cache', et al. }
return { headers: authHeaders }
}
}
最后,您的后端服务(这是快速的,但对于原始节点应该类似地工作):
async function(request, response) {
const increments = [ 1,2,3,4 ];
response.set('Content-Type', 'text/html');
for (const value of increments) { //contains async call - not switch-outable for a forEach.
response.write(`increment - ${value} `);
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
await delay(1000)
}
response.status(200).end()
}
运行时浏览器控制台输出:
- 增量-1
- 增量-1增量-2
- 增量-1增量-2增量-3
- 增量-1增量-2增量-3增量-4
很抱歉有错别字——我不得不从一台锁着的机器上转录出来。