尝试/如何将图像文件从Angular前端发布到.NET CORE后端API-

问题描述 投票:0回答:1

我想知道什么是最好的方法。

[从Angular 8应用程序中,我正在选择一个img文件,并希望将此图像文件发送到.NET Core API后端。后端服务应将此img保存在数据库。

用于我的图像选择器的html-

<div class="image-picker" (click)="fileInput.click()">
  <mat-icon [class.small]="imageUrl">file_upload</mat-icon>
  <canvas width="500" height="380" #canvas hidden="true"></canvas>
  <input #fileInput type="file" hidden="true" (change)="imageDataChanged($event)">
</div>

各自的.ts代码-

imageDataChanged($event) {
    var file = $event.target.files[0];


    console.log(file);

    var reader = new FileReader();

    // get data from file input and emit as dataUrl
    reader.addEventListener("load", () => {
      var ctx = this.canvas.nativeElement.getContext('2d');
      this.imageUrl = reader.result;
      this.imagePicked.emit(this.imageUrl);
    }, false);

    if (file) {
      reader.readAsDataURL(file);
    }
  }

所以我进入控制台,了解与我选择的文件有关的详细信息。像名称,大小,日期,修改日期.....单击提交按钮后,我想将此文件发布到后端API。我的问题是-格式和方式如何。 base64图片?那是什么代码。我该怎么做。就像我说的那样,我的后端位于.NET Core中。

这是我尝试的代码-

[HttpPost]
        [Route("CaptureSaveImg")]
        public IActionResult CaptureSaveImg(HttpContext context)
        {
            string imageName = null;
            var httpRequest = context.Request;

            var postedFile = httpRequest.Form.Files["Image"];

            try
            {
                if(postedFile!=null)
                {
                    var fileName = postedFile.FileName;

                    var myUniqueFileName = Convert.ToString(Guid.NewGuid());

                    var fileExtension = Path.GetExtension(fileName);

                    var newFileName = string.Concat(myUniqueFileName, fileExtension);

                    var filepath = Path.Combine(_environment.WebRootPath, "CameraPics") + $@"\{newFileName}";

                    if (!string.IsNullOrEmpty(filepath))
                    {
                        // Storing Image in Folder  
                        StoreInFolder(postedFile, filepath);
                    }

                    var imageBytes = System.IO.File.ReadAllBytes(filepath);
                    if (imageBytes != null)
                    {
                        StoreInDatabase(imageBytes);
                    }

                    return Json(new { Success = true, Message = "Image Saved." });
                }
                else
                {
                    return Json(new { Success = false, Message = "An error occurred while saving the image." });
                }
            }
            catch(Exception exp)
            {
                return Json(new { Success =false, Message="An unexpected error occurred!"});
            }
        }


private void StoreInDatabase(byte[] imageBytes)
        {
            try
            {
                if (imageBytes != null)
                {
                    string base64String = Convert.ToBase64String(imageBytes, 0, imageBytes.Length);
                    string imageUrl = string.Concat("data:image/jpg;base64,", base64String);
                    ImageStore imageStore = new ImageStore()
                    {
                        CreateDate = DateTime.Now,
                        ImageBase64String = imageUrl,
                        ImageId = 0
                    };
                    _context.ImageStores.Add(imageStore);
                    _context.SaveChanges();
                }
            }
            catch (Exception exp)
            {
                throw exp.InnerException;
            }
        }

        private void StoreInFolder(IFormFile file, string fileName)
        {
            try
            {
                using (FileStream fs = System.IO.File.Create(fileName))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
            }
            catch (Exception exp)
            {
                throw exp.InnerException;
            }

        }

html单击按钮-

<button class="btn btn-primary btn-lg btn-block" type="button" (click)="OnSubmit(Image)" >UPLOAD</button>

。ts用于按钮单击-

OnSubmit(file: File)
  {
    this.userRestService.uploadImage(this.fileToUpload)
      .subscribe((data: any) => {
        console.log('Done successfully! '+data.Message);
        this.imageUrl = null;
      });
  }

在使用休息服务中-

fileToUpload: File = null;  

uploadImage(file: File) {
    var reqHeader = new HttpHeaders({ 'No-Auth': 'True' });

    const formData: FormData = new FormData();
    formData.append('Image', file, file.name);

    return this.http.post(this.baseUrl +'CaptureSaveImg', formData, { headers: reqHeader });
  }

我想先将其保存在本地文件夹路径中,然后从那里读取文件并保存在DB中。我确实明白,当我尝试将其发布为fileToUpload,可能发送的是null。

我面临的问题-我要从前端发布/发送什么到API。怎么样。您能告诉我一些实现此目的的代码吗?您能给我一步一步的指导来实现这一目标。

随时询问我所尝试的更多细节,以获得更好的见解。谢谢

更新:

我早先忘了提到,我的图像选择器组件基本上是一个单独的角度组件,正如我在主页中所使用的那样。因此,imageDataChanged($ event)代码也位于该组件中。我发帖。

<input #fileInput type="file" hidden="true" (change)="imageDataChanged($event)">

。ts代码-

imageDataChanged($event) {
    var file = $event.target.files[0];
    this.ds.selectedFile = file;

    if (file.length===0) {
      return;
    }

    var reader = new FileReader();

    // get data from file input and emit as dataUrl
    reader.addEventListener("load", () => {
      var ctx = this.canvas.nativeElement.getContext('2d');
      this.imageUrl = reader.result;
      this.imagePicked.emit(this.imageUrl);
    }, false);

    if (file) {
      reader.readAsDataURL(file);
    }

    const formData = new FormData();

    formData.append(file.name, file);

    this.ds.formDataPost = formData;

  }

这里ds只不过是一个中间数据共享可注入类。

@Injectable()
export class DataSharingService {

  public selectedFile: any;

  public formDataPost: any;

}

现在,我的OnSubmit代码-

OnSubmit()
  {
    console.log(this.ds.formDataPost);

    const uplRequest = new HttpRequest('POST', this.baseUrl + '/CaptureSaveImg', this.ds.formDataPost, { reportProgress: true });

    this.http.request(uplRequest)
      .subscribe((data: any) =>
      {
        if (data.Success == "true")
        {
          console.log("Upload successful.");
        }
        else
        {
          console.log("Problem while uploading file.");
        }
      })
  }

我刚收到错误-core.js:6014错误TypeError:您在需要流的地方提供了“未定义”。您可以提供一个Observable,Promise,Array或Iterable。

我想我很近。需要转换吗?还是数据格式?

angular image http .net-core asp.net-core-2.0
1个回答
0
投票

我已经通过将数据库保存为Base 64来完成此操作。这很方便,因为在将客户端上的映像立即转换为字符串后,将其发布到服务器并保存到数据库中是很简单的。

myForm = new FormGroup({
  foo: new FormControl(''), // etc...
  imageBase64: new FormControl('')
});

constructor(private cd: ChangeDetectorRef) { }

onImageAttached(event): void {
  const reader = new FileReader();

  if (event.target.files && event.target.files.length) {
    const [file] = event.target.files;
    reader.readAsDataURL(file);

    reader.onload = () => {
      this.myForm.patchValue({
        imageBase64: reader.result
      });

      // need to run CD since file load runs outside of zone
      this.cd.markForCheck();
    };
  }
}

稍后,如果您正在应用程序中显示这些图像,则可以将该base64字符串一直发送到DOM。

另一方面,如果您有一台Web服务器渲染您的Angular客户端,出于性能原因,您也可以将其转换为服务器上的文件。这为您提供了图像的应用程序路由。

public class AppImageController : Controller
{
    [HttpGet]
    public async Task<IActionResult> Index(int id)
    {
        var imageBase64 = await _imageRepository.GetByIdAsync(id);

        var mimeStartIndex = imageBase64.IndexOf("image/");

        var mime = imageBase64
            .Substring(
                mimeStartIndex,
                result.Data.Attachment.IndexOf(';') - mimeStartIndex
             );

        var content = imageBase64
            .Remove(0, result.Data.Attachment.LastIndexOf(',') + 1);

        var bytes = Convert.FromBase64String(content);

        return File(bytes, mime.Length > 0 ? mime : "image/png");
    }
}
<img src="AppImage/Index/{{appImage.id}}"
     alt="{{appImage.name}}">

这并不是说将图像保存到数据库始终是最好的选择。保存到服务器文件系统,AWS S3文件存储等都是非常可行的选择。您可以研究这些方法之间的权衡。

© www.soinside.com 2019 - 2024. All rights reserved.