加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用angular2将图像上传到asp.net核心

发布时间:2020-12-15 21:07:12 所属栏目:百科 来源:网络整理
导读:所以我有angular2的asp.net核心应用程序.现在我想上传图片,如果我将其上传为byte [],我就设法这样做了.但后来我无法检查文件是否真的是后端的图像所以我试图寻找另一种解决方案..我发现这个博客关于文件上传: https://devblog.dymel.pl/2016/09/02/upload-f
所以我有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>

然后我的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;
    });
}

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

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

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

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

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

‘userChange.File.ContentDisposition’ threw an exception of type ‘System.NullReferenceException’

更新1

不知怎的,我设法使用这个答案发送文件到asp.net控制器:File upload using Asp.Net Core Web API file is always null但是这样做我不得不创建另一个没有参数的动作,但是如何在我的情况下发送文件仍然是未知的…

解决方法

我在寻找类似的东西时找到了你的帖子,并且也开始使用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.");
    }
}

调用上传服务:

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

哪个帖子到我的ImagesController的’Upload’ActionResult,看起来像这样(我将我的图像保存到数据库,所以’path’变量实际上是多余的). “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("~ClientAppappassetsimages",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);
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读