从Angular2 app上传文件到Lumen API

前端之家收集整理的这篇文章主要介绍了从Angular2 app上传文件到Lumen API前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个API(流明),它需要一个文件字段在正文中.

使用Postman,我只需将文件解析为API,然后Lumen将其保存在服务器上.

但是如何使用Angular2将文件上传到API?目前我正在使用HTTP来进行后期请求.

this.http.post(ENDPOINT,body,options).....

解决方法

请尝试以下方法.

模板:

<input type="file" 
        id="file"
        (change)="onInputFile($event)">

码:

onInputFile(event){
    let file = event.target.files[0];

    uploadFile(file).then(
       (res:any) => { console.log(res);},(error:any) => { console.log(error);}
    )
}

uploadFile(file,url) {
    return new Promise((success,reject) => {
        let formData = new FormData();
        formData.append('myFile',file);

        let xhr = new XMLHttpRequest();

        xhr.onload = function(){
            if(this.status == 200){
                success(this.response);
            } else {
                reject(this.statusText);
            }
        }

        xhr.onerror = function(){
            reject(this.statusText);
        }

        xhr.open('POST',url,true);
        xhr.send(formData);
    });
}

希望它会有所帮助.

更新:

there is a “angular-way” to do it with the http-class…

Angular2文档说:POST主体实际上必须是一个字符串.您可以尝试将文件转换为base64并发布.

uploadFile(file,url){
        let req = this.http;
        let reader = new FileReader();

        reader.readAsDataURL(file);

        reader.onload = function() {
            req.post(url,reader.result).toPromise();
        };

        reader.onerror = function(error) {
            console.log('Error: ',error);
        };   
    }

猜你在找的Angularjs相关文章