Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试/如何将图像文件从Angular前端发布到.NET CORE后端API--_Angular_Image_Http_.net Core_Asp.net Core 2.0 - Fatal编程技术网

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

尝试/如何将图像文件从Angular前端发布到.NET CORE后端API--,angular,image,http,.net-core,asp.net-core-2.0,Angular,Image,Http,.net Core,Asp.net Core 2.0,我想知道做这件事的最好方法是什么 从Angular 8应用程序中,我正在选择一个img文件,并希望将此图像文件发送到.NET Core API后端。后端服务应在中保存此img 数据库 我的图像选择器的html- <div class="image-picker" (click)="fileInput.click()"> <mat-icon [class.small]="imageUrl">file_upload</mat-icon> <canva

我想知道做这件事的最好方法是什么

从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>
因此,我进入控制台,查看与我选择的文件相关的详细信息。例如名称、大小、日期、修改日期。。。。。单击提交按钮后,我想将此文件发布到后端API。我的问题是——以什么形式和方式。base64图像?代码是什么。我该怎么做呢。正如我所说,我的后端在.NETCore中

这是我尝试的代码-

[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>
OnSubmit(file: File)
  {
    this.userRestService.uploadImage(this.fileToUpload)
      .subscribe((data: any) => {
        console.log('Done successfully! '+data.Message);
        this.imageUrl = null;
      });
  }
正在使用rest服务-

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)">
这里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 error-TypeError:您在需要流的地方提供了“undefined”。您可以提供一个可观察的、承诺的、数组的或可观察的。


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

我通过将数据库保存为Base 64来实现这一点。这很方便,因为在您将客户机上的图像立即转换为字符串后,向服务器发布并保存到数据库是很简单的

myForm=newformgroup({
foo:newformcontrol(“”),//等。。。
imageBase64:新表单控件(“”)
});
构造函数(私有cd:ChangeDetectorRef){}
onImageAttached(事件):无效{
const reader=new FileReader();
if(event.target.files&&event.target.files.length){
const[file]=event.target.files;
reader.readAsDataURL(文件);
reader.onload=()=>{
this.myForm.patchValue({
imageBase64:reader.result
});
//需要运行CD,因为文件加载在区域外运行
这个.cd.markForCheck();
};
}
}
稍后,如果在应用程序中显示这些图像,则可以将base64字符串一直发送到DOM

另一方面,如果有一个web服务器呈现Angular客户端,出于性能原因,还可以将其转换为服务器上的文件。这为您的图像提供了一个应用程序路径

公共类AppImageController:控制器
{
[HttpGet]
公共异步任务索引(int-id)
{
var imageBase64=wait_imageRepository.GetByIdAsync(id);
var mimeStartIndex=imageBase64.IndexOf(“image/”);
var mime=imageBase64
.子串(
模仿指数,
result.Data.Attachment.IndexOf(“;”)-mimeStartIndex
);
var content=imageBase64
.Remove(0,result.Data.Attachment.LastIndexOf(',')+1);
var bytes=Convert.FromBase64String(内容);
返回文件(字节,mime.Length>0?mime:“image/png”);
}
}


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

hi@AdamDunkerley感谢您的回复-让我通读一下您发布的方法。在我这边试试。我会带着我所面临的任何进展/麻烦回来;至于保存到DB部分,是的,除了将图像保存在本地文件夹结构中之外,我只是将其作为一个额外的保证措施。让我尝试合并您建议的代码,您好@AdamDunkerley-我在主要答案中更新了我的代码。请看一看。现在有1个错误,您可以指定该错误发生的时间吗?你知道是哪部分代码引起的吗?您可能需要设置一些控制台日志,以便找到未索引的参数。当我单击按钮将图像提交给API时,就会出现这种情况。事实上,我将我的按钮类型设置为“按钮”而不是“提交”,以避免不必要的麻烦。“让我试着弄一些控制台日志,我会发布它们,”AdamDunkerley说
@Injectable()
export class DataSharingService {

  public selectedFile: any;

  public formDataPost: any;

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