使用angular2上传图像到asp.net核心 [英] uploading image with angular2 to asp.net core

查看:125
本文介绍了使用angular2上传图像到asp.net核心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我使用angular2的asp.net核心应用程序。现在我想上传图片,如果我将其上传为byte [],我就设法这样做了。但后来我无法检查文件是否真的是后端的图像,所以我试图寻找另一种解决方案..我发现这个关于文件上传的博客: https://devblog.dymel.pl/2016/09/02/upload-file-image-angular2-aspnetcore/ 但它对我不起作用...

So I have asp.net core application with angular2. Now I want to upload image and I managed to do so if I upload it as byte[]. But then I can't check if file is realy image in backend so I tried to look for another solutions.. I found this blog about file upload: https://devblog.dymel.pl/2016/09/02/upload-file-image-angular2-aspnetcore/ but it does not work for me...

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

For file upload I use angular2 library angular2-image-upload, so my html part of image upload looks like this:

<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>

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

then my angular2 part looks like this:

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;
    });
}

我的angular2 api电话看起来像这样:

my angular2 api call looks like this:

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 });
}

我的asp.net核心控制器(请注意,我不是显示控制器的主体,因为它是无关紧要的):

my asp.net core controller (NOTE that I'm not showing the body of controller because it is irrelevant):

[HttpPost]
public async Task<IActionResult> UpdateUser([FromBody]UserChange userChange)
{ 
}

UserChange class:

UserChange class:

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; }
}

问题是当我提交图像时,我总是得到我的UserChange对象为null。 当我将图像添加为byte []时,它就像一个魅力有什么问题?为什么即使我传递的文件不是null,我也总是为空?我看到的其他事情,当我将类型从IFormFile更改为FormFile时,我的UserChange对象不再为null,但只有来自object的File参数抛出此错误

The thing is that when I submit my image, I always getting my UserChange object as null. When I was adding image as byte[] it worked like a charm what is the problem?? Why I am getting always null even if I'm passing the file that is not null? Other thing that I saw that when I change the type from IFormFile to FormFile my UserChange object is not null anymore but only File parameter from object is throwing this error


'userChange.File.ContentDisposition'抛出了'System.NullReferenceException'类型的异常

'userChange.File.ContentDisposition' threw an exception of type 'System.NullReferenceException'

UPDATE 1

我设法使用以下答案将文件发送到asp.net控制器:使用Asp.Net Core Web API文件的文件上传始终为null 但为此我必须创建另一个没有参数的动作,但是如何在我的情况下发送文件仍然是未知的...

Somehow I managed to send file to asp.net controller using this answer: File upload using Asp.Net Core Web API file is always null but to do so I had to create another action that has no parameters, but how to send file in my situation is still unknown...

推荐答案

你是不能发送的二进制数据到服务器用json,因为Json不支持二进制数据。

You are cannot send binary data to server with json, because Json not supported binary data.

说明此处

Description Here

但你可以尝试发送' multipart / form-data '

示例代码.net Core Api:

 public class FormModel
 {
        public int Id { get; set; }
        public string Title{ get; set; }
        public string Url { get; set; }
        public bool IsDeleted { get; set; }
        public IFormFile File { get; set; }
 }

 [HttpPost]
 public IActionResult Post([FromForm] FormModel formModel)
 {
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        //** your server side code **//

        return Ok();
  }

示例代码Angular Http发布您的表单数据

  const formData = new FormData();
  formData.append('File', this.file[0] // your input file data);
  formData.append('Id', this.Id.value // your form id value);
  formData.append('Title', this.Title.value // your form title value);
  formData.append('Url', this.Url.value // your form url value)

  const options = new RequestOptions();
  options.headers = new Headers();
  options.headers.append('enctype', 'multipart/form-data');

  this.http.post('your api url', formData, options) {
     // your return value
  }

这篇关于使用angular2上传图像到asp.net核心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆