Upload File Angular 2

2019-07-24 14:08发布

Currently playing around with Angular 2 RC.

Is there any tutorial/article that would help me understand uploading a file to the back-end via a REST call?

I've been through this, but it feels like there should be a more convenient way of doing it.

1条回答
The star\"
2楼-- · 2019-07-24 14:42

If you wait for RC2, you will have the ability to use other payloads than text ones.

For example Blob ones:

var headers = new Headers({'Content-Type': 'text/css'});
var body = new Blob(['body { color: red; }']);

return this.http.post('/url', body, { headers });

Arraybuffer ones:

var headers = new Headers({'Content-Type': 'text/css'});

var body = new ArrayBuffer(512);
var longInt8View = new Uint8Array(body);
for (var i = 0; i < longInt8View.length; i++) {
  longInt8View[i] = i % 255;
}

return this.http.post('/url', body, { headers });

FormData ones:

var body = new FormData();
body.append('test1', 'val1');
body.append('test2', 123456);
var blob = new Blob(['body { color: red; }'], {type: 'text/css'});
body.append("userfile", blob);

return this.http.post('/url', body, { headers });

It would much easier to handle binary content for HTTP requests. Right now, it's difficult (and hacky) since Angular2 only accepts text payloads as input.

查看更多
登录 后发表回答