繁体   English   中英

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

[英]Trying to/How To post an Image file from Angular front end to .NET CORE Backend API --

我想知道这样做的最佳方法是什么。

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

我想先将它保存在本地文件夹路径中,然后从那里读取文件并保存在数据库中。 我知道,当我尝试将其发布为 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 错误类型错误:您在需要流的地方提供了“未定义”。 您可以提供 Observable、Promise、Array 或 Iterable。

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

我通过以 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 文件存储等都是非常可行的选择。 您可以研究这些方法之间的权衡。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM