简体   繁体   中英

Upload File Angular 2

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM