POST负载上的base64图像为空-Angular

时间:2018-07-03 13:09:17

标签: angular post base64

在将图像转换为base64之后,我试图将图像发送到后端,但是在POST有效负载上,图像似乎是null

user.photo = btoa(image);
console.log('user: ', user);    // user.photo is correct
this.userService.updateUser(user).subscribe(data => {   // user.photo is null
    this.currentUser = data;
}

我也尝试了较小的图像(0,8 kB),问题仍然存在,因此我认为问题与图像的大小无关。有人可以请教出什么问题吗?谢谢!

1 个答案:

答案 0 :(得分:0)

此问题不是由于图像尺寸引起的。 UI端的base64转换需要一些改进,或者您调用的API格式错误。请查看下面的代码以验证API。

 public IHttpActionResult updateUser([FromBody] updateUserModel model)
    {
//model object should have a property of type byte[], for example :- 
// public byte[] File { get; set; }

var fileData = model.File;

}

在角度侧,应将数据类型用作绑定到base64Byte数组的属性的“ any”。我在这里分享我的工作代码:-

export class LogoImage {
Id: number;
File: any;
TempFile: any;
FileSize: number;
FileType: string;
FilePath: string;

}     //在更改后的浏览按钮上调用此函数

onFileChange(fileInput: any) {
    let fileName = fileInput.target.files[0].name;
    let fileSize = fileInput.target.files[0].size;
    var ext = fileName.split('.').pop().toUpperCase();

    var self = this;
    if (fileInput.target.files && fileInput.target.files[0]) {
        var reader: any = new FileReader();

        reader.onload = function (e) {


            self.file = e.target.result;

      // following code removes the base64 substring and gives only byte array.
         // it removes data:image/png;base64, from begining 
            this.LogoImage.File = self.file.substring(self.file.indexOf(',') + 1);

    //Initiate the JavaScript Image object.
            var image = new Image();

            //Set the Base64 string return from FileReader as source.
            image.src = e.target.result;

            //Validate the File Height and Width.
            image.onload = function (element) {
                let height = image.height;
                let width = image.width;
     // validation for height and width
                return true;
            };
        }
        reader.readAsDataURL(fileInput.target.files[0]);
    }
}

// html

 <div class="btn-fil-upload btn-file btn-info btn-sm">
                                                    <span class="fileinput-new">Select a file to upload</span>
                                                    <input #fileinputControl tabindex="5" class="fileinput" type="file" (change)="onFileChange($event)" name="..." />
                                                </div>

enter image description here

enter image description here