用angular2上传图像到asp.net核心

Nik*_*ias 5 c# asp.net file-upload image angular

所以我有带有angular2的asp.net核心应用程序。现在,我想上传图像,如果我以byte []的形式上传,我设法做到了。但是后来我无法检查文件是否是后端的真实图像,因此我尝试寻找其他解决方案。.我找到了有关文件上传的博客:https : //devblog.dymel.pl/2016/09/02/upload- file-image-angular2-aspnetcore /,但对我不起作用...

对于文件上传,我使用angular2库angular2-image-upload,所以图像上传的html部分如下所示:

<image-upload [max]="1" [buttonCaption]="'Browse'" [preview]="false" (change)="onFileChange($event)"></image-upload>
<button (click)="onSaveChanges()" class="btn btn-primary float-left" type="submit">Save</button>
Run Code Online (Sandbox Code Playgroud)

然后我的angular2部分看起来像这样:

onFileChange(event: any) {
    this.file = event.target.files[0];

    if (event.target.files && this.file) {
        var reader = new FileReader();

        reader.onload = (event: any) => {
            this.profilePicture = event.target.result;
        }
        reader.readAsDataURL(this.file);
    }
}

onSaveChanges() {
    this.isSaving = true;
    this.country = this.state.user.country;
    this.userService.userChange(this.firstName, this.lastName, this.country, this.file, this.currentPassword, this.newPassword).subscribe(success => {
        this.state.user.profilePicture = this.profilePicture;
        this.state.user.firstName = this.firstName;
        this.state.user.lastName = this.lastName;
        this.isSaving = false;
        this.passwordError = false;
        this.isSuccessful = true;
        this.currentPassword = '';
        this.newPassword = '';
        this.newPasswordRepeat = '';
    }, error => {
        this.isSaving = false;
        this.passwordError = true;
        this.passwordErrorMessage = error._body;
    });
}
Run Code Online (Sandbox Code Playgroud)

我的angular2 api调用看起来像这样:

userChange(firstName: string, lastName: string, country: string, file: File, oldPassword: string, newPassword: string) {
    let input = new FormData();
    input.append("File", file);

    var url = this.baseUrl + "updateUser";

    return this.http.post(url, { FirstName: firstName, LastName: lastName, Country: country, File: input, OldPassword: oldPassword, NewPassword: newPassword });
}
Run Code Online (Sandbox Code Playgroud)

我的asp.net核心控制器(请注意,由于它不相关,所以我不显示其主体):

[HttpPost]
public async Task<IActionResult> UpdateUser([FromBody]UserChange userChange)
{ 
}
Run Code Online (Sandbox Code Playgroud)

UserChange类:

public class UserChange
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string Country { get; set; }

    public IFormFile File { get; set; }

    public string OldPassword { get; set; }

    public string NewPassword { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

问题是,当我提交图像时,我总是将UserChange对象设置为null。当我将图像添加为byte []时,它像一个符咒一样工作,这是什么问题?为什么即使传递不为null的文件,我也总是为null?我看到的另一件事是,当我将类型从IFormFile更改为FormFile时,我的UserChange对象不再为null,而是仅对象中的File参数引发此错误

'userChange.File.ContentDisposition'引发了类型'System.NullReferenceException'的异常

更新1

我以某种方式设法使用以下答案将文件发送到asp.net控制器:使用Asp.Net Core Web API文件上传的文件始终为null, 但要这样做,我不得不创建另一个没有参数的操作,但是如何在我的文件中发送文件情况仍然未知...

小智 0

我在想做类似的事情时发现了你的帖子,并且也开始使用 angular2-image-upload 库,但决定首先尝试简单的方法。出于我的目的,我只需要 byte[] 图像文件(接下来将尝试添加图像标题和标题的表单字段),并发现 Michael Dymel 在他的博客文章中建议的一些内容非常有用,并使其正常工作。尽管你的方法没能发挥作用,但这对我帮助很大。

我遇到困难的是正确路由的配置,有一段时间,我的文件似乎在角度服务上被正确拾取,但当它到达“上传”控制器时却为空。一旦我检查了上传服务的路径和控制器的 [Route("/api/upload")] 属性中定义的路径是否相同,一切就就绪了,我能够成功上传。与您遇到的问题略有不同,但这对我有用:

我的上传组件方法:

addFile(): void {
    let fi = this.fileInput.nativeElement;
    if (fi.files && fi.files[0]) {
        let fileToUpload = fi.files[0];

        if (fileToUpload) {
            this.uploadService.upload(fileToUpload)
            .subscribe(res => {
                console.log(res);
            });
        }
        else
            console.log("FileToUpload was null or undefined.");
    }
}
Run Code Online (Sandbox Code Playgroud)

调用上传服务:

upload(fileToUpload: any) {
        let input = new FormData();
        input.append("fileForController", fileToUpload);
        return this.http.post("/api/upload", input );
    }
Run Code Online (Sandbox Code Playgroud)

它发布到我的 ImagesController 的“上传”ActionResult,如下所示(我将图像保存到数据库中,因此“路径”变量实际上是多余的)。“Image”对象只是 Url、Title、ImageFileContent 和 Caption 字段的简单模型:

[HttpPost]
[Route("/api/upload")]
public async Task<IActionResult> Upload(IFormFile fileForController)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    if (fileForController == null) throw new Exception("File is null");
    if (fileForController.Length == 0) throw new Exception("File is empty");

    var theImage = new Image();
    var path = Path.Combine("~\\ClientApp\\app\\assets\\images\\", fileForController.FileName);

    theImage.Url = path + fileForController.FileName;
    theImage.Title = fileForController.Name + "_" + fileForController.FileName;
    theImage.Caption = fileForController.Name + " and then a Surprice Caption";

    using (Stream stream = fileForController.OpenReadStream())
    {
        using (var reader = new BinaryReader(stream))
        {
            var fileContent = reader.ReadBytes((int)fileForController.Length);

            theImage.ImageFileContent = fileContent;
            _context.Images.Add(theImage);

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
    return Ok(theImage);
}
Run Code Online (Sandbox Code Playgroud)

我的 html 模板字段几乎与 Michael Dymel 的帖子完全相同:

<form action="gallery" name="fileUploadForm" method="post" enctype="multipart/form-data">
    <div class="col-md-6">
        <input #fileInput type="file" title="Choose Image to upload" />
        <button (click)="addFile()" class="btn btn-success">Add</button>
    </div>
</form>
Run Code Online (Sandbox Code Playgroud)